13

I am working on uploading image using multipart. This Code Working fine in swift 4 and Alamofire 4. Please give any solution for this.

public class func callsendImageAPI(param:[String: Any],arrImage:[UIImage],imageKey:String,URlName:String,controller:UIViewController, withblock:@escaping (_ response: AnyObject?)->Void){ Alamofire.upload(multipartFormData:{ MultipartFormData in for (key, value) in param { MultipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key) } for img in arrImage { guard let imgData = img.jpegData(compressionQuality: 1) else { return } MultipartFormData.append(imgData, withName: imageKey, fileName: FuncationManager.getCurrentTimeStamp() + ".jpeg", mimeType: "image/jpeg") } },usingThreshold:UInt64.init(), to: "URL", method:.post, headers:["Content-type": "multipart/form-data", "Content-Disposition" : "form-data"], encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, , ): upload.uploadProgress(closure: { (Progress) in print("Upload Progress: \(Progress.fractionCompleted)") }) upload.responseJSON { response in switch(response.result) { case .success(_): let dic = response.result.value as! NSDictionary if (dic.object(forKey: "status")! as! Int == 1){ withblock(dic.object(forKey: "data") as AnyObject) }else if (dic.object(forKey: Message.Status)! as! Int == 2){ print("error message") }else{ print("error message") } case .failure(_): print("error message") } } case .failure(let encodingError): print("error message") } })} 

Thanks in advance.

2 Answers 2

12

Almofire 5.0 & Swift 5.0

 //Set Your URL let api_url = "YOUR URL" guard let url = URL(string: api_url) else { return } var urlRequest = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: 10.0 * 1000) urlRequest.httpMethod = "POST" urlRequest.addValue("application/json", forHTTPHeaderField: "Accept") //Set Your Parameter let parameterDict = NSMutableDictionary() parameterDict.setValue(self.name, forKey: "name") //Set Image Data let imgData = self.img_photo.image!.jpegData(compressionQuality: 0.5)! // Now Execute AF.upload(multipartFormData: { multiPart in for (key, value) in parameterDict { if let temp = value as? String { multiPart.append(temp.data(using: .utf8)!, withName: key as! String) } if let temp = value as? Int { multiPart.append("\(temp)".data(using: .utf8)!, withName: key as! String) } if let temp = value as? NSArray { temp.forEach({ element in let keyObj = key as! String + "[]" 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(imgData, withName: "file", fileName: "file.png", mimeType: "image/png") }, with: urlRequest) .uploadProgress(queue: .main, closure: { progress in //Current upload progress of file print("Upload Progress: \(progress.fractionCompleted)") }) .responseJSON(completionHandler: { data in switch data.result { case .success(_): do { let dictionary = try JSONSerialization.jsonObject(with: data.data!, options: .fragmentsAllowed) as! NSDictionary print("Success!") print(dictionary) } catch { // catch error. print("catch error") } break case .failure(_): print("failure") break } }) 

Happy to help you :)

Its Work for me

Sign up to request clarification or add additional context in comments.

Comments

9

Please refer Below code.

public class func callsendImageAPI(param:[String: Any],arrImage:[UIImage],imageKey:String,URlName:String,controller:UIViewController, withblock:@escaping (_ response: AnyObject?)->Void){ let headers: HTTPHeaders headers = ["Content-type": "multipart/form-data", "Content-Disposition" : "form-data"] AF.upload(multipartFormData: { (multipartFormData) in for (key, value) in param { multipartFormData.append((value as! String).data(using: String.Encoding.utf8)!, withName: key) } for img in arrImage { guard let imgData = img.jpegData(compressionQuality: 1) else { return } multipartFormData.append(imgData, withName: imageKey, fileName: FuncationManager.getCurrentTimeStamp() + ".jpeg", mimeType: "image/jpeg") } },usingThreshold: UInt64.init(), to: URL.init(string: URlName)!, method: .post, headers: headers).response{ response in if((response.error != nil)){ do{ if let jsonData = response.data{ let parsedData = try JSONSerialization.jsonObject(with: jsonData) as! Dictionary<String, AnyObject> print(parsedData) let status = parsedData[Message.Status] as? NSInteger ?? 0 if (status == 1){ if let jsonArray = parsedData["data"] as? [[String: Any]] { withblock(jsonArray as AnyObject) } }else if (status == 2){ print("error message") }else{ print("error message") } } }catch{ print("error message") } }else{ print(response.error!.localizedDescription) } } } 

Happy to help you :)

2 Comments

Hello, how to get the progress of uploading?
I spent more mins to find why i can't get response even error also nil, finally i found. Here it is, Need to change as "if((response.error == nil))" instead "if((response.error != nil))", But you saved my time thank you @dixit

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.