我正在尝试发送POST请求,以便用户可以登录此应用。但是,当我尝试发送信息时,服务器返回一条错误消息,指出它没有收到登录信息。我之前使用过这个完全相同的代码,但是网址是HTTPS而不是HTTP。 swift 2有不同的方法来处理HTTP请求吗?
在我的info.plist文件中,我添加了以下内容:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
api调用在除iOS之外的每个设备上都能正常工作,并且代码可以正常使用不同的URL。如果Swift 2不再接受HTTP请求,那还有解决方法吗?
static let URL = "http://url.com:3000"
static let netSession = NSURLSession.sharedSession() // A shared NSURLSession that will be used to make API calls
// Call to login with the provided credentials. If login is successful the handler function will
// receive 'true', otherwise 'false'.
static func login(email : String, password : String, handler : (success: Bool, error: APIError?) -> ()) {
let request = NSMutableURLRequest(URL: NSURL(string: "\(URL)/users/login")!)
request.HTTPMethod = "POST"
let params = ["email":email,"password":password]
request.HTTPBody = try? NSJSONSerialization.dataWithJSONObject(params, options: [])
netSession.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if error != nil {
handler(success: false, error: APIErrorNetwork)
return
}
let jsonResponse = JSON(data: data!)
let httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
// Handle the expected response
} else {
handler(success: false, error: APIError(json: jsonResponse))
print(httpResponse.statusCode);
}
}).resume()
}
答案 0 :(得分:2)
您确定服务器是否接受JSON
?它是否希望您发布表单数据?
如果确实需要JSON
,请尝试在您的请求中添加Content-Type
标头:
request.setValue("application/json", forHTTPHeaderField: "Accept");
有些服务器很挑剔。