【发布时间】:2017-05-17 07:27:43
【问题描述】:
我正在尝试将音频文件发布到 API,但出现错误 “*** 由于未捕获的异常‘NSInvalidArgumentException’而终止应用程序,原因:‘JSON 写入 (NSURL) 中的类型无效’” 这是我的代码:
let parameters = [fileUrl]
//create the url with NSURL
let url = NSURL(string: "httpblahblah")
//create the session object
let session = URLSession.shared
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
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 {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
【问题讨论】:
-
我建议您使用此功能,您可以使用 alamofire 第三方库