我有一个应用程序,可以在Xcode6-Beta1和Xcode6-Beta2与iOS7和iOS8上正常工作。但是对于Xcode6-Beta3, Beta4, Beta5,我在iOS8上面临网络问题,但在iOS7上一切都很好。我得到错误“网络连接丢失”。错误如下:
Error: ErrorDomain =NSURLErrorDomain Code=-1005 "The network connection was lost."UserInfo=0x7ba8e5b0 {NSErrorFailingURLStringKey=, _kCFStreamErrorCodeKey=57, NSErrorFailingURLKey=, NSLocalizedDescription=网络连接丢失。, _kCFStreamErrorDomainKey=1, NSUnderlyingError=0x7a6957e0 "The network connection was lost."}
我使用AFNetworking 2。X和下面的代码片段进行网络调用:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager setSecurityPolicy:policy];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:<example-url>
parameters:<parameteres>
success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(@“Success: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"Error: %@", error);
}];
我尝试了NSURLSession,但仍然收到相同的错误。
参见pjebs 1月5日在Github上的评论。
Method1:
if (error.code == -1005)
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
dispatch_group_t downloadGroup = dispatch_group_create();
dispatch_group_enter(downloadGroup);
dispatch_group_wait(downloadGroup, dispatch_time(DISPATCH_TIME_NOW, 5000000000)); // Wait 5 seconds before trying again.
dispatch_group_leave(downloadGroup);
dispatch_async(dispatch_get_main_queue(), ^{
//Main Queue stuff here
[self redoRequest]; //Redo the function that made the Request.
});
});
return;
}
也有人建议重新连接该网站,
即触发POST请求两次
解决方法:使用一个方法做连接到站点,返回(id),如果网络连接丢失,返回使用相同的方法。
方法2
-(id) connectionSitePost:(NSString *) postSender Url:(NSString *) URL {
// here set NSMutableURLRequest => Request
NSHTTPURLResponse *UrlResponse = nil;
NSData *ResponseData = [[NSData alloc] init];
ResponseData = [NSURLConnection sendSynchronousRequest:Request returningResponse:&UrlResponse error:&ErrorReturn];
if ([UrlResponse statusCode] != 200) {
if ([UrlResponse statusCode] == 0) {
/**** here re-use method ****/
return [self connectionSitePost: postSender Url: URL];
}
} else {
return ResponseData;
}
}