How to upload file multipart alamofire swift5?

456 Views Asked by At

I'm trying to send file to the server via multipart. It can be image or an ordinary file. I have some difficulties with URLConvertible usage. As I see Alamofire has such method, which maybe will be useful for me:

AF.upload(multipartFormData: <(MultipartFormData) -> Void>, to: <URLConvertible>)

but here as you can I can't attach interceptor which will handle 401 error. For this purpose I have created such variable:

let manager =  Session(configuration: URLSessionConfiguration.default, interceptor: CallInterceptor.init(method:HTTPMethod.post))

and also created the request:

var request = URLRequest(url: Pathes.init(endpoint: "photo").resourseUrl)
request.httpMethod = HTTPMethod.post.rawValue

and final usage is attached to photo selector:

  func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        guard let fileUrl = info[UIImagePickerController.InfoKey.imageURL] as? URL else { return }
        if let pickedImage = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
 
         .....


          manager.upload(multipartFormData: { (formData) in
                formData.append(fileUrl, withName: "photo", fileName: fileName, mimeType: mediaType)
            }, to: request as! URLConvertible).validate(statusCode: 200..<300)
            .responseJSON(completionHandler: { (response) in
                print(response.debugDescription)
            })


}

}

but as a result my app crashes with such error:

Could not cast value of type 'Foundation.URLRequest' (0x7fff85d1dbd8) to 'Alamofire.URLConvertible' (0x7ffb558a5320)

I think I have two ways: use another AF method or created another request type. But I can't imagine which method will help me one one side and on another side I don't know how to create URLConvertible. I thought that I can do it in such way:

 let urlRequest: Alamofire.URLRequestConvertible = request

but the app crashed again. What I did wrong?

2

There are 2 best solutions below

5
Jon Shier On

If you want to use a URLRequest and not a URL you need to use the appropriate upload overload: upload(multipartFormData:with:).

manager.upload(multipartFormData: { (formData) in
                formData.append(fileUrl, withName: "photo", fileName: fileName, mimeType: mediaType)
    }, with: request)
2
Hafeez Shaik On

let PDFUrl = URL(string: "file://(yourdirectoryurl)") let myData = try Data(contentsOf: PDFUrl! as URL)

            let data : Data = myData
            multipartFormData.append(data as Data, withName: "files", mimeType:"application/pdf")