Alamofire 4 — Multipart file upload with Swift 3

Dejan Atanasov
Swift2Go
Published in
3 min readJul 2, 2017

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)

--

--

Dejan Atanasov
Swift2Go

Senior iOS & Android Developer | Creator of Swift2Go | @hackernoon writer | Hire Me: http://bit.ly/2XfxbBR