Search code examples
jsonswiftalamofireimage-uploadingmultipartform-data

alamofire upload images with json parameters


I am new to swift I want to upload images (from 1 to 4 - depending on user) and a video file(if user prefer) to my server and also send other parameters when uploading (like text and etc.) in android I was using retrofit which allowed me to use @partmap for uploading my nested Json objects. now in iOS I am using Alamofire but I couldn't find this functionality to send json with multipart how can I should do this? I don't want base 64 image I already tried this and my text content are nested clearly I want to send json parameters when uploading data for example:

image 1 = image
post->content = "some text"

Solution

  • As I mentiontioned in comments you need a multipart request.

    // Image file which you want to upload.
    guard let image = UIImage(named: "YourImage") else { return }
    
    
                    let imgRep : NSBitmapImageRep = image.representations.first as! NSBitmapImageRep
    
                    let imgData : Data = imgRep.representation(using: .PNG, properties: [:])!
    
    
                    let cameraFileName    = "some_random_name_img.png"
    
                    let fileUrl = URL(fileURLWithPath: cameraFileName, isDirectory: true)
                    do {
    
                        try imgData.write(to: fileUrl, options: NSData.WritingOptions.atomic)
    
                        DispatchQueue.main.async {
                            // Stop Camera Session if you are capturing image from camera
                            self.cameraSession.stopRunning()
    
                            let someParam   = ""
                            let someParam2  = ""
    
    
                            let date = Date()
                            let dateString = "\(date)"
    
    
    
                            Alamofire.upload(multipartFormData: { (multipartFormData) in
    
                            // Add parameters in request 
    
             multipartFormData.append(cameraFileName.data(using: .utf8)!, withName: "name")
    
             multipartFormData.append(dateString.data(using: .utf8)!, withName: "startDatetime")
    
             multipartFormData.append(someParam.data(using: .utf8)!, withName: "userId")
    
             multipartFormData.append(someParam2.data(using: .utf8)!, withName: "phoneServiceId")
    
             multipartFormData.append(fileUrl, withName: "file")
    
                            }, to:"Your_Api_Url.com") // POST Url
                            { (result) in
                                switch result {
                                case .success(let upload, _ , _):
    
                                    upload.uploadProgress(closure: { (progress) in
    
                                        print("uploding")
                                    })
    
                                    upload.responseJSON { response in
                                        print(response)
                                        print("done")
    
    
    
    
    
    
                                    }
    
                                case .failure(let encodingError):
                                    print("failed")
                                    print(encodingError)
    
                                }
                            }
    
                        }
    
                    }
                    catch let error as NSError {
                        print("Ooops! Something went wrong: \(error)")
                    }