I'm trying to upload an image with parameters in Swift. I have a problem with an array in the parameters
post request look like this.
curl --request POST \
--url http://example.com/api/v2/upload-single-photo-restaurant \
--header 'Accept: application/json' \
--header 'content-type: multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' \
--form lat=21.584739 \
--form lng=105.807110 \
--form device_id=TG23X44C \
--form name=Kitacy \
--form 'datetime=2018-05-15 08:54:00' \
--form 'categories[]=1' \
--form 'categories[]=2' \
--form photo=undefined
link code: https://ideone.com/mSGWkD
This is my current code
func myImageUploadRequest()
{
let myUrl = URL(string: "https://example.com/api/v2/upload-single-photo-restaurant");
let request = NSMutableURLRequest(url:myUrl!);
request.httpMethod = "POST";
let device_id = UIDevice.current.identifierForVendor!.uuidString
print("lat is:",lat!)
print("lng is:",lng!)
var param:[String:Any] = [
"lat" : lat!,
"lng" : lng!,
"device_id" : device_id,
"name" : photoName.text!,
"datetime" : Const.getDate()
] as [String : Any]
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
let imageData = UIImageJPEGRepresentation(imgView.image!, 1)
if(imageData==nil) { return; }
request.httpBody = createBodyWithParameters(parameters: param as? [String : String], filePathKey: "photo", imageDataKey: imageData! as NSData, boundary: boundary) as Data
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("error=\(String(describing: error))")
return
}
// You can print out response object
print("******* response = \(String(describing: response))")
// Print out reponse body
let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("****** response data = \(responseString!)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: []) as? NSDictionary
print(json!)
DispatchQueue.main.async(execute: {
self.imgView.image = UIImage(named: "img")
let msg = json?.object(forKey: "message")
UIViewController.removeSpinner(spinner: self.sv!)
self.stackViewUpload.isHidden=true
self.alertWithMsg(msg: msg as! String)
})
}catch{
print(error)
}
}
task.resume()
}
func createBodyWithParameters(parameters: [String: String]?, filePathKey: String?, imageDataKey: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
body.appendString(string: "\(value)\r\n")
}
}
let filename = "user-profile.jpg"
let mimetype = "image/jpg"
body.appendString(string: "--\(boundary)\r\n")
body.appendString(string: "Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
body.appendString(string: "Content-Type: \(mimetype)\r\n\r\n")
body.append(imageDataKey as Data)
body.appendString(string: "\r\n")
body.appendString(string: "--\(boundary)--\r\n")
return body
}
extension NSMutableData {
func appendString(string: String) {
let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
append(data!)
}
}
link code: https://ideone.com/CPj1CO
Now how can I add a category(Integer) array to the 'categories []' key into the parameters ?