mvasco
mvasco

Reputation: 5101

App crashes if string value contains character '&'

I am working with JSON array received from a PHP file on a web server.

This is the code I am using for this:

NSMutableString *ms = [[NSMutableString alloc] initWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/comprobartipo.php?id="];
    NSString *tipo=[[view annotation] title];
     NSString* urlTextEscaped = [tipo stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [ms appendString:urlTextEscaped];
    NSLog(@"TIPO ES AQUI %@", urlTextEscaped);


    NSURLRequest *request1 = [NSURLRequest requestWithURL:[NSURL URLWithString:ms]];

    [NSURLConnection sendAsynchronousRequest:request1 queue:[NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse *response, NSData *data1, NSError *connectionError) {
        if (data1) {
            NSArray *array = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];
            NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]);
            NSLog(@"ESTO ES DATA en If %@",data1);
        }else{
            NSLog(@"ESTO ES DATA en ELSE %@",data1);
            // Tell user there's no internet or data failedN
            NSLog(@"NO HAY CONEXION");
        }
    }];

The code is working fine, but the app crashes if the string value for NSString *tipo contains a character like &.

Error:

'NSRangeException', reason: '* -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

Any help to avoid this issue is welcome.

Upvotes: 0

Views: 85

Answers (1)

Natarajan
Natarajan

Reputation: 3271

Your crash will be here,

NSArray *array = [NSJSONSerialization JSONObjectWithData:data1 options:0 error:nil];

NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]); // Crash will be here

You should check your array whether it has objects or not.

Let's try as below

if (array.count)
    NSLog(@"PROCEDENCIA DESDE INTERNET %@", [array objectAtIndex:0]);

Thanks!

Upvotes: 1

Related Questions