I'm new to swift and I'm doing my best to learn fast. right now I'm struggling with multipart form data.i have an API which has a ticket system, it takes 2 String and one Integer and One fileData(Picture). the server admin says I have to use a multipart form data to have a successful POST request.
I'll be thankful if anybody could help me with the code. the API Address is: http://app.avatejaratsaba1.com/api/Ticket/SendTicket it works fine in postman but when I try the postman code for swift , I get some errors?!
UPDATE:
let headers = [
"content-type": "multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW",
"Cache-Control": "no-cache",
"Postman-Token": "ed42f6a7-a01c-432f-82f4-bed9560814e1"
]
let parameters = [
[
"name": "Title",
"value": "abcd3"
],
[
"name": "Description",
"value": "a"
],
[
"name": "Unit",
"value": "1"
],
[
"name": "FileData",
"fileName": "/Users/Am1rFT/Desktop/Screen Shot 2018-07-06 at 1.14.03 AM.jpg"
]
]
let boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
var body = ""
var error: NSError? = nil
for param in parameters {
let paramName = param["name"]!
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"\(paramName)\""
if let filename = param["fileName"] {
let contentType = param["content-type"]!
let fileContent = String(contentsOfFile: filename, encoding: String.Encoding.utf8)
if (error != nil) {
print(error)
}
body += "; filename=\"\(filename)\"\r\n"
body += "Content-Type: \(contentType)\r\n\r\n"
body += fileContent
} else if let paramValue = param["value"] {
body += "\r\n\r\n\(paramValue)"
}
}
let request = NSMutableURLRequest(url: NSURL(string: "http://app.avatejaratsaba1.com/api/Ticket/SendTicket")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "POST"
request.allHTTPHeaderFields = headers
request.httpBody = postData as Data
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
Update
UPDATE:
if let filename = param["fileName"] {
let contentType = param["content-type"]
do{
let fileContent = try String(contentsOfFile: filename as! String , encoding: String.Encoding.utf8)
if (error != nil) {
print(error as Any)
}
in this part of the code i get
" Thread 1: signal SIGABRT "
and in the console it shows :
" Could not cast value of type 'UIImage' (0x1b4c9ad50) to 'NSString' (0x1b4c767b8)."