Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alamofire 3.0 ReactiveCocoa Conversion

I'm having a lot trouble converting my old Alamofire 2.0 to 3.0 in ReactiveCocoa. I keep getting an unknown identifier error on my sendNext and sendCompleted calls.

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))
                }
        }
    }
}
}
like image 738
Brady coye Avatar asked Nov 17 '15 04:11

Brady coye


2 Answers

This syntax changed in 4.0 alpha 2. Observer is now its own type so the old functions sendNext, sendError, etc are no longer free functions:

switch result {
case .Success(let value):
    observer.sendNext(value)
    observer.sendCompleted()
case .Failure(_, let error):
    observer.sendError(NetworkError(error: error))
}

One thing I would add to your solution is to provide a disposable so that requests can be cancelled if needed, to save resources:

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)
}
like image 193
NachoSoto Avatar answered Nov 09 '22 21:11

NachoSoto


Try observer.sendNext(value) and ditto for sendCompleted and sendError

like image 20
Schpaencoder Avatar answered Nov 09 '22 21:11

Schpaencoder