Search code examples
iosreachabilityafnetworking-2afhttprequestoperation

iOS: reachability for AFNetworking


I' doing a 'Batch of Operations' in this way and it work fine

NSMutableArray *mutableOperations = [NSMutableArray array];
    for (NSString *stringURL in url_list) {

        NSURL *url = [NSURL URLWithString:stringURL];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];

        AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
        operation.responseSerializer = [AFHTTPResponseSerializer serializer];
        [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

            [self addDataToTotal:[self parseJSONfile:responseObject]];

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];

        [mutableOperations addObject:operation];
    }

    NSArray *operations = [AFURLConnectionOperation batchOfRequestOperations:mutableOperations progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {
        NSLog(@"progress:%f", (float)numberOfFinishedOperations / totalNumberOfOperations);
    } completionBlock:^(NSArray *operations) {
        NSLog(@"All operations in batch complete");
        [self startPopulateDBStructure:self.total];
    }];
    [[NSOperationQueue mainQueue] addOperations:operations waitUntilFinished:NO];

now I want to use the 'reachability property' to check the connection status and I do this

[[[NSOperationQueue mainQueue]reachabilityManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusReachableViaWWAN:
            case AFNetworkReachabilityStatusReachableViaWiFi:
                [[NSOperationQueue mainQueue] setSuspended:NO];
                break;
            case AFNetworkReachabilityStatusNotReachable:
            default:
                [[NSOperationQueue mainQueue] setSuspended:YES];
                break;
        }
    }];

but I obtain a crash with this message, where is the problem?

[NSOperationQueue reachabilityManager]: unrecognized selector sent to instance

Solution

  • You are trying to get the reachabilityManager from the main NSOperationQueue, which doesn't have it. You should be using [AFNetworkReachabilityManager sharedManager] to get the reachabilityManager instance.


    So:

    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) { ...
    

    Also, consider the logic of trying to suspend the main queue. What you probably want to be doing is getting the operationQueue from your AFHTTPRequestOperationManager instance and suspending that...