Search code examples
swiftmultipartform-datarx-swiftmoya

unable to upload file RXSwift Moya multipart


I'm using Moya for handling communication between my swift application and api, I'm able to post and get data but unable to post file to api server, following is my code

enum TestApi {
    ...
    case PostTest(obj: [String: AnyObject])
    ...
}

extension TestApi: TargetType {

    var baseURL: NSURL {
        switch self {
            case .PostTest:
                return NSURL(string: "http://192.168.9.121:3000")!
        }
    }

    var path: String {
        switch self {
            case .PostTest:
                return "/api/file"
        }
    }

    var method: Moya.Method {
        switch self {
            case .PostTest:
                return .POST
        }
    }

    var parameters: [String: AnyObject]? {
        switch self {
            case .PostTest(let obj):
                return ["image": obj["image"]!]
        }
    }

    var sampleData: NSData {
        return "".dataUsingEncoding(NSUTF8StringEncoding)!
    }

    var multipartBody: [MultipartFormData]? {
        switch self {
            case .PostTest(let multipartData):

                guard let image = multipartData["image"] as? [NSData] else { return[] }

                let formData: [MultipartFormData] = image.map{MultipartFormData(provider: .Data($0), name: "images", mimeType: "image/jpeg", fileName: "photo.jpg")}
                return formData


            default:
                return []
        }
    }
}

and following is the way I called

return testApiProvider.request(.PostTest(obj: _file)).debug().mapJSON().map({ JSON -> EKResponse? in
    return Mapper<EKResponse>().map(JSON)
})

I dont receive no response and no hit was sent to the api server


Solution

  • the subscription is missing in the calling code. This is not really a Moya problem, but problem with Reactive Extensions. the following .subscribeNext { _ in } fixed my issue

    return testApiProvider
        .request(.PostTest(obj: _file))
        .debug()
        .mapJSON()
        .map({ JSON -> EKResponse? in
            return Mapper<EKResponse>().map(JSON)
        })
        .subscribeNext { _ in }