如果任务因网络故障而暂停,则iOS NSURLSession将恢复任务

时间:2014-10-15 13:29:43

标签: ios xcode nsurlsession

我使用NSURLSessionDataTask从服务器获取数据。我的问题是,如果网络在从服务器接收数据时失败,那么服务器将停止。因此,当网络工作正常时,我该如何恢复任务。正在使用网络Reachability API,但我错过了。

以下是我项目中使用的示例代码:

    //Add the Observer for checking the internet connections
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];

self.wifiReachability = [Reachability reachabilityForLocalWiFi];
[self.wifiReachability startNotifier];

//Starts the downloading the data....
+(void)downloadDataFromURL:(NSURL *)url withCompletionHandler:(void (^)(NSData *))completionHandler{

// Instantiate a session configuration object.
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

// Instantiate a session object.
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];

// Create a data task object to perform the data downloading.
NSURLSessionDataTask *task = [session dataTaskWithURL:url completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

    if (error != nil) {
        // If any error occurs then just display its description on the console.
        NSLog(@"error %@", [error localizedDescription]);
    }
    else{
        // If no error occurs, check the HTTP status code.
        NSInteger HTTPStatusCode = [(NSHTTPURLResponse *)response statusCode];

        // If it's other than 200, then show it on the console.
        if (HTTPStatusCode != 200) {
            NSLog(@"HTTP status code = %ld", (long)HTTPStatusCode);
        }

        // Call the completion handler with the returned data on the main thread.
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            completionHandler(data);
        }];
    }
}];

// Resume the task.
[task resume];

我正在调用通知API来检查网络

-(void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
[self updateInterfaceWithReachability:curReach];
}

- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
  if (reachability == self.internetReachability)
 {
    [self updateInternetActivity:reachability];
 }

  if (reachability == self.wifiReachability)
 {
    [self updateInternetActivity:reachability];

 }
}

- (void)updateInternetActivity:(Reachability *)reachability
{
 NetworkStatus netStatus = [reachability currentReachabilityStatus];
 switch (netStatus)
{
    case NotReachable:        {
        [task suspend];
        break;
    }

    case ReachableViaWWAN:        {
        [task resume];

        break;
    }
    case ReachableViaWiFi:        {
        [task resume];

        break;
    }
}

}

我正在恢复任务,但它没有工作。请提前帮助,谢谢。

0 个答案:

没有答案