Uploading a Large file using Alamofire 5

      No Comments on Uploading a Large file using Alamofire 5

Very large files can not be converted into data at once and moved around in variables. It is simply not possible as very large files could trigger memory warning and eventual crash. Now the question arises how do we upload very large files using Alamofire? Solution is simple just pass the file url to alamofire and it will upload it in chunks. As shown in code below

        let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")

        AF.upload(multipartFormData: { (multipartdata) in
// add any additional parameters first
        //multipartdata.append(<data>, withName: <Param Name>)
            multipartdata.append(fileURL, withName: <Param Name>)
        }, to: "https://httpbin.org/post").responseJSON { (data) in
            print(data)
        }

Uploading a file this way does not require you to move a very large file at once in you memory.This strategy might be over kill for uploading images for which you might be able to convert them to data at once as shown below

 let image = UIImage.init(named: "myImage")
 let imgData = UIImageJPEGRepresentation(image!, 0.2)!
AF.upload(imgData, to: "https://httpbin.org/post").responseDecodable(of: HTTPBinResponse.self) { response in
    debugPrint(response)
}
A pat on the back !!