NSURLDomainError 1005 "The Network Connection Was Lost"
NSURLDomainError 1005 "The Network Connection Was Lost"
我在一个新升级到Swift 2.0的项目中依次执行了以下两个调用。
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()
其次是:
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()
第一个代码块正确执行,returns以下代码:
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";
但是第二个有这个错误:
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.}
我无权访问服务器并尝试了不同的会话和相同的共享会话来发送请求。
有什么想法吗?
这就是错误 1005 的全部要点 - 您无权访问服务器。当您向服务器发送请求时,会发生以下两种情况之一:您可以访问服务器并返回状态代码,或者您的设备永远无法与服务器通信,因此服务器无法为您提供状态代码。相反,您会收到一个错误,通常在 #1000 左右。
这种情况非常罕见,这意味着您的设备开始与服务器通信,然后断开连接(当您下载数兆字节的文件时更常见)。想象一下有人从您的 Mac 中拔出网络电缆,或者想象您在向服务器发出请求的过程中带着您的 iPad 走出 WiFi 范围。
我建议您将 phone 模式更改为 "Airplane" 模式,看看会发生什么 - 每个请求都会收到类似的错误,您应该测试您的应用程序是否能够正常运行。当您关闭 "Airplane" 模式时,它也应该恢复到全部功能。
通过使用 NSURLConnection 而不是 NSURLSession 解决了这个问题。它似乎是由于会话缓存了以前的连接而发生的。
我在一个新升级到Swift 2.0的项目中依次执行了以下两个调用。
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()
其次是:
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()
第一个代码块正确执行,returns以下代码:
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";
但是第二个有这个错误:
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.}
我无权访问服务器并尝试了不同的会话和相同的共享会话来发送请求。
有什么想法吗?
这就是错误 1005 的全部要点 - 您无权访问服务器。当您向服务器发送请求时,会发生以下两种情况之一:您可以访问服务器并返回状态代码,或者您的设备永远无法与服务器通信,因此服务器无法为您提供状态代码。相反,您会收到一个错误,通常在 #1000 左右。
这种情况非常罕见,这意味着您的设备开始与服务器通信,然后断开连接(当您下载数兆字节的文件时更常见)。想象一下有人从您的 Mac 中拔出网络电缆,或者想象您在向服务器发出请求的过程中带着您的 iPad 走出 WiFi 范围。
我建议您将 phone 模式更改为 "Airplane" 模式,看看会发生什么 - 每个请求都会收到类似的错误,您应该测试您的应用程序是否能够正常运行。当您关闭 "Airplane" 模式时,它也应该恢复到全部功能。
通过使用 NSURLConnection 而不是 NSURLSession 解决了这个问题。它似乎是由于会话缓存了以前的连接而发生的。