IOS: Using stringWithContentsOfURL when network is unavailable

251 Views Asked by At

In this code poll from within my app for a reachable network ("http://soxxx9.cafe24.com/event.php")

   NSString * szURL =[NSString stringWithFormat:@"http://soxxx9.cafe24.com/event.php"];

   NSURL *url = [NSURL URLWithString:[szURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding ]];

   NSString *strData;
   while(1)
  {
    NSError *error = nil;
    strData = [NSString stringWithContentsOfURL:url
                                             encoding:NSUTF8StringEncoding
                                                error:&error];
    if(!error)
       break;
    //String data is not owned by me, no need to release
}

If you have a better way, please teach me.

2

There are 2 best solutions below

0
On

You should a class to handle the connection for you. This way you have more control of what's going on with it. MKNetworkKit is a solution, you can check it here.

0
On

This code seems to be heavily power consuming when network is out : you'll try million times to download something that is unreachable...

Have a look at the Reachability class, provided by Apple (http://developer.apple.com/library/ios/#samplecode/Reachability/Introduction/Intro.html). You'll find ARCified versions on gitHub (https://github.com/tonymillion/Reachability for example).

The idea is to register for notifications about the network reachability.

So, in your code :

  1. Check network resource availability before retrieving the string you want.
  2. If this is available, use your code WITHOUT the while(TRUE)
  3. Check your string for any error while retrieving it client side = in your code

If the network is not available, you'll have to inform the user that network is unreachable, and register for reachability notifications to retrieve your string as soon as it is reachable again for example.