-1

My scenario, I am trying to send some parameters with Image Data to server using POST call. Here, I need to update my code Parameters to Body request, because Image base64 string huge data producing so we cant send long lenth data with it. Please update blow code how to upload image and extra parameters to Server.

apiPath = "https://............com/api/new_line?country=\(get_countryID ?? "unknown")&attachment=\("sample.png")&user_id=\(userid ?? "unknown")"

         if let encodeString = apiPath.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed),
            let url = URL(string: encodeString) {

            let session = URLSession.shared
            var request = URLRequest(url: url)
            request.httpMethod = "POST"
            request.addValue("application/json", forHTTPHeaderField: "Content-Type")
            request.addValue("application/json", forHTTPHeaderField: "Accept")
            request.addValue(access_key, forHTTPHeaderField: "access-key")
            request.addValue(auth_token!, forHTTPHeaderField: "auth-token")
            request.timeoutInterval = 10

            let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

                guard error == nil else {return}
                guard let data = data else {return}

                do {
                    //MARK: Create json object from data
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)

                        // MARK: Validate status code
                        let status_code : Int = json["status"]! as! Int
                        let status_message : String = json["message"]! as! String

                        if (status_code != 200) {
                            print("ERROR:\(String(describing: status_code))")
                            DispatchQueue.main.async {
                                self.showMessageToUser(messageStr: status_message)
                            }

                        } else {

                            DispatchQueue.main.async {

                                // Show Success Alert View Controller
                                if self.tfData != "" {  // Call Update

                                    self.apistatus(message:Updated Successfully!")

                                } else {

                                    self.apistatus(message:"Submitted Successfully!")
                                }
                            }
                        }
                    }
                } catch let error {
                    print(error.localizedDescription)
                }
            })
            task.resume()
            }
jackios
  • 155
  • 2
  • 11
  • Thats what for we use [Multi part uploading](https://stackoverflow.com/questions/29623187/upload-image-with-multipart-form-data-ios-in-swift) . You got thousands of example for same if your search google. Try anyone. – dahiya_boy Mar 11 '19 at 09:22
  • https://developer.apple.com/documentation/foundation/url_loading_system/uploading_streams_of_data – Sachin Vas Mar 11 '19 at 09:29

2 Answers2

0

You can try using Alamofire (https://github.com/Alamofire/Alamofire) as below.

Alamofire.upload(
        multipartFormData: { multipartFormData in
            multipartFormData.append(photoData, withName: "photoId", fileName: "photoId.png", mimeType: "image/png")
            for (key,value) in params { //params is a dictionary of values you wish to upload
                multipartFormData.append(value.data(using: .utf8)!, withName: key)
            }   
        },
        to: URL(string : urlString)!,
        method: .post,
        headers: getContentHeader(),
        encodingCompletion: { encodingResult in

            switch encodingResult {

            case .success(let upload, _, _):
                upload.responseJSON { response in
                    if response.response?.statusCode == 200 {
                        print("Success")
                    } else {
                        print("Failure")    
                    }
                }

            case .failure(let error):
                print("Failure")
            }
        }
)
Sujal
  • 1,447
  • 19
  • 34
  • @jackios You can try the solution mentioned here: https://stackoverflow.com/questions/29623187/upload-image-with-multipart-form-data-ios-in-swift – Sujal Mar 11 '19 at 10:08
0
// Iam use alamofire Method
   func sendIMAGeAndParams(urlString:String,imageData:[String:[Data]],header: String,params:[String:AnyObject], success: @escaping (AnyObject) -> Void,failure: @escaping(Error)  -> Void) {
            let param = ["" : ""]
            let url = try! URLRequest.init(url: urlString, method: .post, headers: nil)

            Alamofire.upload(multipartFormData: { (formdata) in
                for (key, value) in params {

                    formdata.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)    
                }

                for (key,value) in imageData{
                    for item in value{
                        formdata.append(item, withName: key, fileName: "image.jpeg", mimeType: "image/jpeg")
                    }
                }

            }, with: url) { (encodingResult) in
                switch encodingResult{
                case .success(let upload,_,_):
                    upload.responseJSON(completionHandler: { (response) in
                        switch response.result{
                        case .success(_):
                            if (response.response?.statusCode == 200){
                                if let value = response.result.value {
                                    success(value as AnyObject)
                                    print(value)
                                }
                            }
                            else{
                                let value = response.result.value as? [String:Any]
                                print(value as Any)
                            }
                            break
                        case .failure(let error):
                            print(error)
                            break
                        }
                    })
                    break
                case .failure(let error):
                    print(error)
                    break
                }
            }

    }
Sukh
  • 1,278
  • 11
  • 19
  • Thank you so much....I am not using Almofire. I am using normal HTTP POST. – jackios Mar 11 '19 at 09:56
  • i found this link :- https://stackoverflow.com/questions/29623187/upload-image-with-multipart-form-data-ios-in-swift – Sukh Mar 11 '19 at 10:09