riksof-zeeshan
riksof-zeeshan

Reputation: 531

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

Upvotes: 2

Views: 1871

Answers (2)

Dhaval Golakiya
Dhaval Golakiya

Reputation: 81

Multipart body is deprecated in Moya 8.0.0. Instead of that use Task for uploading.

Check this issue:

Moya multipart upload target

Upvotes: 2

riksof-zeeshan
riksof-zeeshan

Reputation: 531

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 }

Upvotes: 1

Related Questions