ios - POST with/JSON Body - Swift 3 - 片段?
<p><p>我只是想通过 Swift3 httprequest 发送一个 JSON 字符串。</p>
<p>尝试使用字典和转义字符串 ...</p>
<pre><code>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: = [
"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)
}
}
</code></pre>
<p>我不断得到:</p>
<blockquote>
<p>Handle Error: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did
not start with array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}</p>
</blockquote>
<p>我找不到如何尝试允许片段,所有示例/教程都是针对 Swift2.x 的:/</p>
<p>不知道该怎么办!</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><pre><code>// prepare json data
let mapDict = [ "1":"First", "2":"Second"]
let json = [ "title":"ABC" , "dict": mapDict ] as
do {
let jsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
// create post request
let endpoint: String = "https://yourAPI"
let session = URLSession.shared
let url = NSURL(string: endpoint)!
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "POST"
// insert json data to the request
request.httpBody = jsonData
let task = session.dataTask(with: request as URLRequest){ data,response,error in
if error != nil{
print(error?.localizedDescription)
return
}
}
task.resume()
} catch {
print("bad things happened")
}
</code></pre></p>
<p style="font-size: 20px;">关于ios - POST with/JSON Body - Swift 3 - 片段?,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39949687/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39949687/
</a>
</p>
页:
[1]