views:

16

answers:

1

So I have this piece of code :

if ([receivedPage hasPrefix:[NSString stringWithUTF8String:"\xC3\xAF\xC2\xBB\xC2\xBF"]]) // UTF-8 BOM 'EF BB BF' as UTF-16 chars
    {
        //DebugLog(@"converting calls list to UTF8");
        receivedPage = [[[NSString alloc] initWithData:[receivedPage dataUsingEncoding:NSISOLatin1StringEncoding] encoding:NSUTF8StringEncoding] autorelease];
    }

However sometimes when the if is true the receivedPage becomes null. why would this happen?

The received page is the returned value of this function:

 NSURLResponse * response;
    NSData * result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:error];

    if ([result length] > 0)
        return [[[NSString alloc] initWithBytes: (const void*)[result bytes] length:[result length] encoding: encoding] autorelease];
    else
    {
        if (error && *error)
            DebugLog(@"URL request got error: %@",*error);
        return nil;
    }

The encoding here is NSISOLatin1StringEncoding (don't know why ,I'm debugging someone else's code).

Any idea why this would happen?

A: 

It looks like you're trying to treat strings (objects containing characters) as data (objects containing bytes). Keep the data you received from the connection, and check for the UTF-8 BOM (the proper three-byte version) in it, then use either NSUTF8StringEncoding or NSISOLatin1StringEncoding based on whether you find it.

Or, just use UTF-8 conditionally, if you can fix the server to do that as well.

Also, you should probably switch this code to use the NSURLConnection asynchronously. If the user's internet connection is slow, you're hanging your app here. Doing it asynchronously lets you keep the UI running, display progress if appropriate, and enable the user to cancel.

Peter Hosey