RxAlamofire发布多部分数据

时间:2016-12-28 11:02:59

标签: swift3 alamofire reactive-programming rx-swift rxalamofire

如何使用RxAlamofire发送Multipart数据

  

例如在Alamofire

let URL = try! URLRequest(url: "http://example.com", method: .post)


Alamofire.upload(multipartFormData: { formData in
    // multiaprt
}, with: URL, encodingCompletion: {(result: SessionManager.MultipartFormDataEncodingResult) in

})
  1. 如何使用RxAlamofire获得相同的行为/功能?
  2. 或将此功能包装在Observable中的方法?

1 个答案:

答案 0 :(得分:1)

你可以像这样轻松地包装这个函数:

func wrapper() -> Observable<SomeResponseType> {
    return Observable.create { observer in

        let URL = try! URLRequest(url: "http://example.com", method: .post)

        Alamofire.upload(
            multipartFormData: { formData in
                // multiaprt
            }, 
            with: URL, 
            encodingCompletion: { encodingResult in

                switch encodingResult {

                case .success(let upload, _, _):
                    upload.responseJSON { response in
                        // convert response in something of SomeResponseType
                        // ...
                    observer.onNext(response)
                    observer.onCompleted()
                }
                case .failure(let encodingError):
                    observer.onError(encodingError)
                }
            })

        return Disposables.create()
    }
}