Reputation: 1337
I am trying to send a POST request so that a user can login to this app. However, when I try to send the information, the server returns an error message saying that it did not receive the login information. I have used this exact same code before but with the url having HTTPS instead of HTTP. Does swift 2 have a different method that deals with HTTP requests?
In my info.plist file I have added the following:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key><true/>
</dict>
The api calls work fine on every device except iOS, and the code works fine with a different url. If Swift 2 no longer accepts HTTP requests is there a work around?
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()
}
Upvotes: 1
Views: 711
Reputation: 34935
Are you sure your server accepts JSON
? Does it expect you to post form data instead?
If it does expect JSON
, try to add a Content-Type
header to your request:
request.setValue("application/json", forHTTPHeaderField: "Accept");
Some servers are picky.
Upvotes: 2