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()
}