gpt4 book ai didi

ios - POST w/JSON Body - Swift3 - 片段?

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:38:02 25 4
gpt4 key购买 nike

我只是想通过 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)
}
}

我不断得到:

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.}

我找不到如何尝试允许片段,所有示例/教程都是针对 Swift2.x 的:/

不确定该怎么做!

最佳答案

// prepare json data
let mapDict = [ "1":"First", "2":"Second"]

let json = [ "title":"ABC" , "dict": mapDict ] as [String : Any]

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")
}

关于ios - POST w/JSON Body - Swift3 - 片段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39949687/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com