Alamofire 4 â Multipart file upload with Swift 3
Previously I have introduced you to Alamofire and how you can use it to simple HTTP requests and intercept JSON responses. Today, we will speak for a more complex and a must-know topic â how to create a Multipart File Upload request.
Multipart File Upload request
HTTP multipart file upload request is a request that HTTP clients construct to send files and data over to HTTP Server. It is commonly used by HTTP clients to upload files to the server.
In this tutorial, I am showing you how to construct a multipart file upload request, previously tested by me in many other projects so I can guarantee that it is working. This is a copy-paste solution but I would like to explain a bit what is going on. Before we start, donât forget to install Alamofire and call import Alamofire in your file.
Arguments
I have created this function to support as many arguments as possible. I will start by order:
- endUrl: String â I suppose you are keeping your base URL in some other helper function (for this presentation I have hard coded it in the url variable), so this argument will be for attaching the endpoint to your base URL.
- imageData: Data? â this is an argument that you need to pass your UIImage converted in a Data type. It is optional, so you can pass nil if you donât have an image to pass.
- parameters: [String : Any] â an argument where you need to pass your additional key value POST parameters. Pass an empty key â value object, if you donât have any.
- onCompletition â a closure block where you will pass the success response
- onError â a closure block where you will pass the error response
If you donât know how to convert UIImage to Data, here is a snippet that can help you:
let img = UIImage(named:"someImage.png")
let data = UIImageJPEGRepresentation(img, 1.0)
I really hope that this tutorial helped you discover how to create multipart file upload requests. If you have any questions please leave a comment in the comments section. Also, spread the word by sharing this post or â¤.