Swift moya upload image with body params like on Postman

1.2k views Asked by At

I'm trying to upload image with body params. On postman correctly sending:

Postman

And on Postman Console:

Postman Console

But on calling request on project, Xcode is freezing and not response.

import Moya

protocol BaseTargetType: TargetType { }

extension BaseTargetType {
    
    public var baseURL: URL { URL(string: EnvConfigs.baseUrl)! }
    
    public var path: String { CommonConfigs.urlPath }
    
    public var method: Moya.Method { .post }
    
    public var sampleData: Data { Data() }
    
    public var headers: [String : String]? { nil }
    
    public var validate: Bool { true }
    
    public var requiredToken: Bool { true }
}

enum ImageTarget {
    case upload(data: Data, type: String)
}

extension ImageTarget: BaseTargetType {
    var task: Task {
        switch self {
        case let .upload(data, _):
            let model = Model(userFile: data)
            // here
            return .requestJSONEncodable(model)
        }
    }
}

struct Model: Codable {
    var action: String = "upload_photo"
    var type: String = "3"
    var userFile: Data
}

How to correctly send Image with body params like on Postman?

1

There are 1 answers

0
Evgeny Karkan On BEST ANSWER

You may notice that in Postman ContentType header's value is set to multipart/form-data.
Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).

So you need to use .uploadMultipart task to achieve it using Moya.
There is a code sample in Moya docs.