我目前正在嘗試使用JSON正文在iOS平臺上發出POST請求。我的請求使用cURL,但我無法在iOS中使用它;請求超時。這裏是我的SWIFT代碼:iOS URLRequest POST失敗Swift
class func createNewChannel(name: String, priv: String, channelKey: String, handle: String, password: String, auth: String) {
let baseURL = "http://10.0.0.220:3000/"
let dict = ["name": name, "private": priv, "channelKey": channelKey, "handle": handle, "password": password, "auth": auth] as [String : Any]
let jsonData = JSON(dict)
do {
let post = try jsonData.rawData()
let postLength = String(post.count)
let url = URL(string: "\(baseURL)channel/createChannel")!
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = post as Data
request.setValue(postLength, forHTTPHeaderField: "Content-Length")
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
let session = URLSession.shared
let task = session.dataTask(with: request, completionHandler: { (data, response, error) in
if error == nil {
do {
let json = try JSON(data: data!)
print(json)
}
catch {
print(error.localizedDescription)
}
}
else {
print(error!)
}
})
task.resume()
}
catch {
print(error.localizedDescription)
}
}
當我調用此函數,該請求不工作...我相信我使用的是正確的網址,因爲它有一個GET端點工作。我是否缺少任何標題?如果您發現請求出現問題,請告訴我。
感謝您的回答......我很抱歉地說,即使您的方法請求仍然超時。任何其他想法? –