我在Reactive
Cocoa中将旧的Alamofire 2.0转换为3.0时遇到了很多麻烦.我在sendNext和sendCompleted调用中不断收到未知标识符错误.
public final class Network: Networking { private let queue = dispatch_queue_create( "Beet.BeetModel.Network.Queue",disPATCH_QUEUE_SERIAL) public init() { } public func requestJSON(url: String,parameters: [String : AnyObject]?) -> SignalProducer<AnyObject,NetworkError> { return SignalProducer { observer,disposable in let serializer = Alamofire.Request.JSONResponseSerializer() Alamofire.request(.GET,url,parameters: parameters) .response(queue: self.queue,responseSerializer: serializer) { _,_,result in switch result { case .Success(let value): sendNext(observer,value) sendCompleted(observer) case .Failure(_,let error): sendError(observer,NetworkError(error: error)) } } } } }
这个语法
changed in
4.0 alpha 2
. Observer现在是它自己的类型,所以旧函数sendNext,sendError等不再是自由函数:
switch result { case .Success(let value): observer.sendNext(value) observer.sendCompleted() case .Failure(_,let error): observer.sendError(NetworkError(error: error)) }
我要为您的解决方案添加的一件事是提供一次性使用,以便在需要时可以取消请求,以节省资源:
return SignalProducer { observer,disposable in let serializer = Alamofire.Request.JSONResponseSerializer() let request = Alamofire.request(.GET,parameters: parameters) request.response(queue: self.queue,responseSerializer: serializer) { _,result in switch result { case .Success(let value): observer.sendNext(value) observer.sendCompleted() case .Failure(_,let error): observer.sendError(NetworkError(error: error)) } } disposable.adddisposable(request.cancel) }