Pergunta

NSError *error;
NSString *string = [[NSString alloc]
                    initWithContentsOfURL:URL
                    encoding:NSUTF8StringEncoding
                    error:&error];

When I test this on my iPhone it always works when I have wifi turned on. However when I'm on 3G I often get nil. If I try perhaps 15 times in a row (I have an update button for this) I finally get the desired result.

My question is, is this problem located at the server side or is my code unstable? Should I use a different approach to get a more secure fetch of data?

Foi útil?

Solução 2

I'm now using STHTTPRequest instead. I recommend this library very much, easy to use yet powerful.

Outras dicas

You haven't provided enough information to give anything but a vague answer, but you do have some options here.

Most importantly, you have an "error" parameter that you should be printing out the results of. There's also a slightly better API you could be using in the NSString class.

Change your code to something like this:

NSError *error = NULL;
NSStringEncoding actualEncoding;

// variable names in Objective-C should usually start with lower case letters, so change
// URL in your code to "url", or even something more descriptive, like "urlOfOurString"
NSString *string = [[NSString alloc] initWithContentsOfURL:urlOfOurString usedEncoding:&actualEncoding error:&error];
if(string)
{
    NSLog( @"hey, I actually got a result of %@", string);

    if(actualEncoding != NSUTF8StringEncoding)
    {
        // I also suspect the string you're trying to load really isn't UTF8
        NSLog( @"and look at that, the actual encoding wasn't NSUTF8StringEncoding");
    }
} else {
    NSLog( @"error when trying to fetch from URL %@ - %@", [urlOfOurString absoluteString], [error localizedDescription]);
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top