Question

I'm trying to figure out how to display a "No internet connection" alert using AFNetworking 2 and Reachability.

I have Reachability and AFNetworking imported into my Controller. The part of my code that starts with AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url]; I copied off of the AFNetworking 2 documentation, I'm not sure if that's where it belongs.

UPDATE

My app now shows an alert whenever theres no internet connection but it takes way too long for the alert to show up, I also doubt this is the best way that I can structure my code. (Also if I'm on the main view Controller and I click on a cell when there's no connection the app crashes, I dont know if there's a way to fix this).

- (void)viewDidLoad

{
    [super viewDidLoad];

    Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];

    reach.reachableBlock = ^(Reachability * reachability)
    {
        NSLog(@"Reachable");
    };

    reach.unreachableBlock = ^(Reachability * reachability)
    {
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No internet connection"
                                                         message:@"No internet connection"
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
        [alert show];
        NSLog(@"Not Reachable");
    };

    [reach startNotifier];

    self.upcomingReleases = [[NSMutableArray alloc] init];

    [self makeReleasesRequests];

    self.navigationController.navigationBar.tintColor = [UIColor whiteColor]; // Make nav items white

    [self.collectionView registerClass:[ReleaseCell class] forCellWithReuseIdentifier:@"ReleaseCell"];
}

-(void)makeReleasesRequests
{
    NSURL *url = [NSURL URLWithString:@"http://www.soleresource.com/upcoming.json"];

    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];

    operation.responseSerializer = [AFJSONResponseSerializer serializer];

    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSLog(@"@");

        self.upcomingReleases = [responseObject objectForKey:@"upcoming_releases"];

        [self.collectionView reloadData];

    } failure:nil];

    [operation start];

    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:url];

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

}

Thanks.

Was it helpful?

Solution 4

Try this with reachability

Reachability * reach = [Reachability reachabilityWithHostname:@"www.google.com"];

reach.reachableBlock = ^(Reachability * reachability)
{
  UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"Title" message:@"Reachable" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];

  [alrt performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:yes];  
};

reach.unreachableBlock = ^(Reachability * reachability)
{
  UIAlertView *alrt=[[UIAlertView alloc]initWithTitle:@"Title" message:@"Not Reachable" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];

  [alrt performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:yes];  
 };


[reach startNotifier];

OTHER TIPS

I use the AFNetworkingOperationDidFinishNotification. Every time a http request will fail, the alert pops up and informs the user.

- (void)addNetworkObserver
{
   [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(HTTPOperationDidFinish:) 
                                                name:AFNetworkingOperationDidFinishNotification 
                                              object:nil];
}

- (void)HTTPOperationDidFinish:(NSNotification *)notification 
{
   AFHTTPRequestOperation *operation = (AFHTTPRequestOperation *)[notification object];
   if (![operation isKindOfClass:[AFHTTPRequestOperation class]]) {
       return;
   }
   if (operation.error) {
       UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Connection error"
                                                       message:@"Missing connection to the internet"
                                                      delegate:nil
                                             cancelButtonTitle:@"OK"
                                             otherButtonTitles:nil];

       [alert show];
   }
}

ahh I was having the same exact issue, you need to remove [alert show] and add to main thread, so it should look like this,

 UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"No internet connection"
                                                         message:@"No internet connection"
                                                        delegate:self
                                               cancelButtonTitle:@"Ok"
                                               otherButtonTitles:nil];
       // [alert show];
        NSLog(@"Not Reachable");
        [alert performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES];

If you're using AFNetworking 3.0, call this code on ViewDidLoad or your AppDelegate :

// Monitoring Reachability
[[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
    NSLog(@"Reachability: %@", AFStringFromNetworkReachabilityStatus(status));

    // Add your alert here
}];

[[AFNetworkReachabilityManager sharedManager] startMonitoring];

Make sure you're calling startMonitoring on the reachabilityManager (stick with the one built in to AFNetworking 2, adding in Reachability is redundant in this case).

[manager.reachabilityManager startMonitoring]

You can test this out by toggling on/off airplane mode on your device or simulator. Keep in mind, this won't handle cases with timeouts/slow connections/bad requests. That's something you'll have to handle along with this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top