Alamofire 3.0 ReactiveCocoa转换

时间:2015-11-17 04:02:11

标签: swift alamofire reactive-cocoa

我在Alamofire 2.0中将旧的3.0转换为ReactiveCocoa时遇到了很多麻烦。我在sendNextsendCompleted来电时收到了未知标识符错误。

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))
                }
        }
    }
}
}

2 个答案:

答案 0 :(得分:11)

此语法changed in 4.0 alpha 2Observer现在是它自己的类型,因此旧函数sendNextsendError等不再是自由函数:

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, url, 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)
}

答案 1 :(得分:2)

尝试observer.sendNext(value)并同时sendCompletedsendError