我只是尝试通过Swift3 httprequest发送JSON字符串。
尝试使用词典和转义字符串......
func getToken(successHandler: @escaping (Any) -> Void, errorHandler: @escaping (Any) -> Void) {
var request = URLRequest(url: URL(string: "http://my-api.domain.com/getToken")!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
do
{
// try with Dictionary
let bodyJson: [String: String] = [
"username": "theusername"
]
let bodyJsonData = try JSONSerialization.data(withJSONObject: bodyJson, options: [])
// try with escaped String
let jsonString = "{" +
"\"username\": \"theusername\"," +
"}"
let jsonStringData = jsonString.data(using: String.Encoding.utf8)
//request.httpBody = bodyJsonData
request.httpBody = jsonStringData
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error)
errorHandler(error)
return
}
guard let data = data else {
print("Data is empty")
errorHandler("Data is empty")
return
}
var json: Any? = nil
do
{
json = try JSONSerialization.jsonObject(with: data, options: [])
DispatchQueue.main.asyncAfter(deadline: .now()) {
successHandler(json)
}
}
catch let error as NSError {
errorHandler(error)
}
}
task.resume()
}
catch
{
errorHandler(error)
}
}
我一直在:
处理错误:错误域= NSCocoaErrorDomain代码= 3840" JSON文本确实如此 不要从数组或对象和选项开始,以允许未设置片段。" UserInfo = {NSDebugDescription = JSON文本不是以数组或 允许片段未设置的对象和选项。}
我无法找到如何尝试允许片段,所有示例/教程都适用于Swift2.x:/
不确定该怎么做!
答案 0 :(得分:4)
{{1}}