Uploading Files in Swift 5 with Alamofire

Uploading files is an essential feature of many applications, and it can be challenging to implement it correctly. Fortunately, with Alamofire, uploading files in Swift 5 is relatively easy. In this tutorial, we will guide you through the process of uploading a file using Alamofire in Swift 5.

Step 1: Import Alamofire and MobileCoreServices frameworks

To use Alamofire for file uploads, you must first import the Alamofire and MobileCoreServices frameworks. MobileCoreServices provides support for handling various file types and MIME types.

import Alamofire
import MobileCoreServices

Step 2: Create a multipart upload request

Next, you need to create a multipart upload request using the Alamofire.upload method. In this example, we will upload a PNG image file named “image.png” to a server endpoint URL.

let fileUrl = Bundle.main.url(forResource: "image", withExtension: "png")!
let uploadUrl = URL(string: "https://example.com/upload")!

Alamofire.upload(
    multipartFormData: { multipartFormData in
        multipartFormData.append(fileUrl, withName: "file", fileName: "image.png", mimeType: "image/png")
    },
    to: uploadUrl,
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                debugPrint(response)
            }
        case .failure(let encodingError):
            print(encodingError)
        }
    }
)

The code above creates a multipartFormData object that includes the file URL, name, filename, and MIME type. Then, the Alamofire.upload method is called with the multipartFormData object, the upload URL, and an encoding completion handler. The handler switches on the encoding result and either prints an error or a debug response.

Step 3: Add Authorization header if necessary

If your server endpoint requires authorization, you can add an Authorization header to the upload request. Here’s an example of how to add a basic authorization header:

let username = "your-username"
let password = "your-password"
let credentialData = "\(username):\(password)".data(using: .utf8)!
let base64Credentials = credentialData.base64EncodedString(options: [])

let headers: HTTPHeaders = [
    "Authorization": "Basic \(base64Credentials)",
    "Accept": "application/json"
]

Alamofire.upload(
    multipartFormData: { multipartFormData in
        // ...
    },
    to: uploadUrl,
    headers: headers,
    encodingCompletion: { encodingResult in
        // ...
    }
)

Step 4: Monitor upload progress

To monitor the upload progress, you can use the uploadProgress method of the upload object returned by Alamofire.upload. Here’s an example of how to print the upload progress:

upload.uploadProgress { progress in
    print("Upload Progress: \(progress.fractionCompleted)")
}

In this tutorial, we covered the basics of uploading files in Swift 5 with Alamofire. By following the steps outlined above, you should be able to upload files to your server endpoint using Alamofire with ease.

A pat on the back !!