我是新手,我正在尽力快速学习。现在我正在处理多部分表单数据。我有一个带有票务系统的API,它需要2个String和一个Integer和一个fileData(Picture)。服务器管理员说我必须使用多部分表单数据才能成功执行POST请求。
如果有人可以帮助我编写代码,我将不胜感激。 API地址为:http://app.avatejaratsaba1.com/api/Ticket/SendTicket,在邮递员中可以正常使用,但是当我尝试将邮递员代码进行swift时,会出现一些错误?!
更新:
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()
更新
更新:
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)
}
在这部分代码中,我得到
“线程1:信号SIGABRT”
并在控制台中显示:
“无法将类型为'UIImage'(0x1b4c9ad50)的值转换为'NSString' (0x1b4c767b8)。”