Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload files with parameters from multipartformdata using alamofire 5 in ios swift

Tags:

I am trying upload files with parameters (multipartformdata) but i can't do it with new version Alamofire 5, if you have some experience with Alamofire 5 please share it with me.

 func uploadPluckImage(imgData : Data, imageColumnName : String,  url:String,httpmethod:HTTPMethod,completionHandler: @escaping (NSDictionary?, String?) -> ()){     let token = UserDefaults.standard.string(forKey: PrefKeys.loginToken) ?? ""     let authorization = ["Authorization" : "Bearer \(token)"]     let parameters: Parameters?     parameters = [         "garbageCollector": 0,         "stuff_uuid": "2b4b750a-f4a6-4d61-84ce-7c42b5c030ee",         "delete_file" : ""     ]     let headers : HTTPHeader?     headers = ["Authorization" : "Bearer \(token)"]     let imageURl = "http://68.183.152.132/api/v1/stuff/uploader"            AF.upload(multipartFormData: { (multipart: MultipartFormData) in         let imageData = self.firstImage.image?.jpegData(compressionQuality: 0.7)             multipart.append(imageData, withName: "file", fileName: "file.png", mimeType: "image/png")                  for (key, value) in parameters!{             multipart.append(value as! String).data(using: .utf8)!, withName: key)         }     },usingThreshold: UInt64.init(),        to: imageURl,        method: .post,        headers: headers,        encodingCompletion: { (result) in         switch result {         case .success(let upload, _, _):             upload.uploadProgress(closure: { (progress) in               print("Uploading")             })             break         case .failure(let encodingError):             print("err is \(encodingError)")                 break             }         }) } 
like image 784
Diaa SAlAm Avatar asked Mar 20 '19 15:03

Diaa SAlAm


People also ask

How to append to multipartformdata in Swift 3?

To append to multipartFormData in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData: public func append (_ data: Data, withName name: String) { /* ... */ } And, to convert String to Data, the data (using:) method of String. E.g., thanks. do you have any example with a URLRequestConvertible parameter?

Is it possible to send a multipart form?

It is also possible to send a multipart form data like so: You can also upload files via Alamofire by simply specifying the file name and it’s extension: let fileURL = Bundle.main.url (forResource: "video", withExtension: "mp4")!

How do I add an alamofire pod to my project?

Now navigate to your project folder and open a terminal window, also navigate the terminal window to the project location. Once there you should do a “pod init” in your terminal It will then output a file named Podfile. Open the Podfile in Textedit and add the line pod “Alamofire”, “ [version number]” or just simply pod “Alamofire”

What is alamofire used for in iOS?

What is Alamofire? Alamofire is an elegant and composable way to interface to HTTP network requests. It builds on top of Apple’s URL Loading System provided by the Foundation framework. At the core of the system is URLSession and the URLSessionTask subclasses.


1 Answers

Upload method slightly changed in Alamofire 5

func upload(image: Data, to url: Alamofire.URLRequestConvertible, params: [String: Any]) {     AF.upload(multipartFormData: { multiPart in         for (key, value) in params {             if let temp = value as? String {                 multiPart.append(temp.data(using: .utf8)!, withName: key)             }             if let temp = value as? Int {                 multiPart.append("\(temp)".data(using: .utf8)!, withName: key)             }             if let temp = value as? NSArray {                 temp.forEach({ element in                     let keyObj = key + "[]"                     if let string = element as? String {                         multiPart.append(string.data(using: .utf8)!, withName: keyObj)                     } else                         if let num = element as? Int {                             let value = "\(num)"                             multiPart.append(value.data(using: .utf8)!, withName: keyObj)                     }                 })             }         }         multiPart.append(image, withName: "file", fileName: "file.png", mimeType: "image/png")     }, with: url)         .uploadProgress(queue: .main, closure: { progress in             //Current upload progress of file              print("Upload Progress: \(progress.fractionCompleted)")         })         .responseJSON(completionHandler: { data in             //Do what ever you want to do with response         }) } 

Hope this will help you

EDIT: In case you don't quite get the above, here is an expansion:

let uploadRequest: UploadRequest = AF.upload(multipartFormData: multipartFormData, with: ...) let completionHander: (AFDataResponse<Any>) -> Void) = { result in     //Do what ever you want to do with response, which is a DataResponse<Success, AFError> } // Adds that completion hander to the UploadRequest uploadRequest.responseJSON(completionHandler: completionHander) 
like image 183
Ajay Singh Mehra Avatar answered Oct 20 '22 00:10

Ajay Singh Mehra