簡體   English   中英

如何使用 NSURLSession 在 Swift 中定義內容類型

[英]How can I define Content-type in Swift using NSURLSession

我想在下面的代碼中設置 content-type 來調用 web api。 內容類型為application/json; charset=utf-8 application/json; charset=utf-8

let url = NSURL(string: "http:/api/jobmanagement/PlusContactAuthentication?email=\(usr)&userPwd=\(pwdCode)")

println("URL:  \(url)")

let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {
    (data, response, error) in
    println(NSString(data: data, encoding: NSUTF8StringEncoding))
}

//  task.setValue(<#value: AnyObject?#>, forKey: <#String#>)
task.resume()

如果您想設置請求的Content-Type ,您可以創建自己的URLRequest ,提供您的 URL,使用setValue(_:forHTTPHeaderField:)指定Content-Type標頭,然后使用URLRequest而不是URL發出請求直接地。 只需將httpBody設置為該 JSON 並指定POSThttpMethod

let url = URL(string: "https://api/jobmanagement/PlusContactAuthentication")!
var request = URLRequest(url: url)
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")        // the expected response is also JSON
request.httpMethod = "POST"

let dictionary = ["email": username, "userPwd": password]
request.httpBody = try! JSONEncoder().encode(dictionary)

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error ?? "Unknown error")                                 // handle network error
        return
    }

    // parse response; for example, if JSON, define `Decodable` struct `ResponseObject` and then do:
    //
    // do {
    //     let responseObject = try JSONDecoder().decode(ResponseObject.self, from: data)
    //     print(responseObject)
    // } catch let parseError {
    //     print(parseError)
    //     print(String(data: data, encoding: .utf8))   // often the `data` contains informative description of the nature of the error, so let's look at that, too
    // }
}
task.resume()

對於 Swift 2 版本,請參閱此答案的先前修訂版

這對我使用 SWIFT 5 進行 API 調用開發 iOS 應用程序很有用。 GET 方法在沒有這兩行的情況下工作正常。 PUT 和 POST 方法會將值發送到 API 服務器,但是一旦到達服務器,它就無法解釋 JSON 數據,因此我的數據庫將為所有字段插入 NULL 值。 添加這兩行后,數據正​​確傳輸到表中。 希望這可以節省其他人的時間。

request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  
request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")  

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM