Reputation: 73
I execute the following two calls one after another in a newly upgraded to Swift 2.0 Project.
let session = NSURLSession.sharedSession()
authRequest.HTTPMethod = "POST"
authRequest.HTTPBody = authData
authRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
authRequest.addValue("close", forHTTPHeaderField: "Connection")
authRequest.addValue("application/json", forHTTPHeaderField: "Accept")
let authTask = session.dataTaskWithRequest(authRequest, completionHandler: { (data : NSData?, response : NSURLResponse? , error : NSError?) -> Void in
print("Response: \(response)")
print("Error: \(error)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
if let httpResponse = response as? NSHTTPURLResponse
{
if 200 ... 299 ~= httpResponse.statusCode
{
do
{
result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! Dictionary
credentials.ClientId = (result["client_id"] as String?)!
credentials.ClientSecret = (result["client_secret"] as String?)!
credentials.Username = userDetail.Username
credentials.Password = userDetail.Password
completionHandler(result: true)
}
catch {
}
}
else
{
self.RemoveInvalidUserCredentials()
completionHandler(result: false)
}
}
})
authTask.resume()
Followed by:
let session = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration())
session.configuration.URLCache = nil
session.configuration.HTTPMaximumConnectionsPerHost = 1
tokenRequest.HTTPBody = tokenData
tokenRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
tokenRequest.addValue("close", forHTTPHeaderField: "Connection")
tokenRequest.addValue("Basic " + (credentials.encodedClientIdAndSecret() as String), forHTTPHeaderField: "Authorization")
let tokenTask = session.dataTaskWithRequest(tokenRequest, completionHandler: {(data : NSData?, response : NSURLResponse? , error : NSError?) -> Void in
print("Response: \(response)")
print("Error: \(error)")
let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
if let httpResponse = response as? NSHTTPURLResponse {
if 200 ... 299 ~= httpResponse.statusCode
{
do
{
result = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as! Dictionary
credentials.TokenType = (result["token_type"] as! String?)!
credentials.Token = (result["access_token"] as! String?)!
completionHandler(result: true)
}
catch{}
}
}
})
tokenTask.resume()
The first code block executes correctly and returns the following:
Response: Optional(<NSHTTPURLResponse: 0x14ffe3e60> { URL: <URL>/authorize } { status code: 200, headers {
"Cache-Control" = "no-cache";
"Content-Length" = 115;
"Content-Type" = "application/json; charset=utf-8";
Date = "Tue, 29 Sep 2015 14:17:52 GMT";
Expires = "-1";
Pragma = "no-cache";
Server = "Microsoft-IIS/7.5";
"Set-Cookie" = ".AspNet.ApplicationCookie=E98BMJ5l56psnnJZRy2fyhRTWVYqw4aJsFqPeV1ktkJGi5_frTJ9-8pbp28TcDAn9ISFj_LqwFwOV7WhP1mfTVPktTGTs2Dr5-hvmnISxFVRc1Rg9CcYf3p-Cbn1w6qOEyuXco9PCmCnlsf54KPuSY6Z7FEcUgOyg2nq5oDyamfB_Y4b1dI-7cIZ3LB6ehoI50rIbc2ca7L7f73H1rhbsmuLRarBYsYehSRHRuKs9ec5-XuN0P1W6yqiQ3OOJMayPmmbi6y4uIhBUu0zoRC2v3k9usmRjubxGy2hqf6n0baTOIDokav0wQq_smR9qDA6nNh09YTS1Mzvf0iQPS2YJa7QrnERlNSixDROhkQVLC8hc3GV8jc9_7iGUhJzLgeVzhnjnVeB7Z311QLcXxGonEzzcWAzPu29tm2LkZgdte4J0kQHc-iTiNjSbgBqV2zVH9v_0JHtZCFGdSxSGptXGfsPr5O9M-EyVX2UNXxIsVI-hfv3p8-_igV96phbWsvWyqyYhVMQ8v61vHxfO2CFIQ; path=/; secure; HttpOnly";
"X-Powered-By" = "ASP.NET";
However the second has this error:
Error Domain=NSURLErrorDomain Code=-1005 "The network connection was lost." UserInfo={NSUnderlyingError=0x14ffe3cc0 {Error Domain=kCFErrorDomainCFNetwork Code=-1005 "(null)" UserInfo={_kCFStreamErrorCodeKey=-4, _kCFStreamErrorDomainKey=4}}, NSErrorFailingURLStringKey=https://test.acumentive.com/tagmanager/api/v1/tokens, NSErrorFailingURLKey=https://test.acumentive.com/tagmanager/api/v1/tokens, _kCFStreamErrorDomainKey=4, _kCFStreamErrorCodeKey=-4, NSLocalizedDescription=The network connection was lost.}
I don't have access to the server and have tried different sessions and the same shared session to send the request.
Any ideas?
Upvotes: 3
Views: 3773
Reputation: 73
Resolved the issue by using NSURLConnection instead of NSURLSession. It appears to be happening due to the session caching the previous connections.
Upvotes: 4
Reputation: 52632
That's the whole point of error 1005 - you have no access to the server. When you send a request to the server, one of two things happens: Either you get access to the server and a status code is returned, or your device never manages to talk to the server, so the server cannot give you a status code. Instead you get an error, usually around #1000.
This one is quite rare, it would mean that your device started talking to the server and then lost the connection (more common when you download a multi megabyte file). Imagine someone pulling a network cable out of your Mac, or imagine you walking out of WiFi range with your iPad, in the middle of a request to the server.
I suggest you change your phone to "Airplane" mode and see what happens - every request will get a similar error, and you should test that your app survives this reasonably well. It should also recover to full functionality when you turn "Airplane" mode off.
Upvotes: 1