Search code examples
swiftalamofiremultipartform-data

Empty request body alamofire multipart


I would like to make such request via alamofire with attaching selected file:

enter image description here

I also have to add interceptor to the request. So, I added below code to my image picker method:

let manager =  Session(configuration: URLSessionConfiguration.default, interceptor: CallInterceptor.init(method:HTTPMethod.post))
manager.upload(multipartFormData: { multipartFormData in
     multipartFormData.append( fileUrl, withName: "upload_doc\"; filename= \"\(fileName)\"")
},
to:Pathes.init(endpoint: "user/photo").resourseUrl.absoluteString).responseJSON(completionHandler: { (completion) in
   print(completion.debugDescription)
})

where:

let fileName = fileUrl.lastPathComponent

in logs I saw such output:

[Request]: POST url
    [Headers]:
        Authorization: Bearer token
        Content-Type: multipart/form-data; boundary=alamofire.boundary.c5da18c6b053a9d7
    [Body]: None
[Response]: None
[Network Duration]: None
[Serialization Duration]: 3.253298928029835e-05s
[Result]: failure(Alamofire.AFError.sessionDeinitialized)

as I see I didn't attach request body what caused such request cancel. How I can add body to the request? I thought that this line:

multipartFormData.append( fileUrl, withName: "upload_doc\"; filename= \"\(fileName)\"")

but it doesn't add body to the request. I also tried adding file directly:

 multipartFormData.append(imgData, withName: "upload_doc\"; filename= \"\(fileName)\"",fileName: fileName, mimeType: "image/jpg")

but this way also sent:

[Body]: None

so the question is how to add some body to multipart request or I have to send file in another way?


Solution

  • The error, .sessionDeinitialized, means that your Session instance was deinited before the request completed. You need to keep it alive, either as an instance value in something else, or a singleton.