views:

36

answers:

1

Hi, I used to have:

NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

But, I was reading online that I should probably be using an NSURLRequest instead if I want to add a timeout. The first code works fine, but the second code always returns @"" (not nil, just ""). Anyone have any suggestions?

I also read that the NSURLConnection takes care of any sort of web compression that might be done whereas NSURLRequest won't handle that, so I thought I better just go for the more well rounded solution. http://lists.apple.com/archives/cocoa-dev/2009/Oct/msg01921.html

    NSString *escapedUrlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *responseString;
    NSURLResponse *response;
    NSError *error;

    NSURLRequest *request = [[NSMutableURLRequest alloc] 
                             initWithURL:[NSURL URLWithString:escapedUrlString]
                             cachePolicy:NSURLRequestUseProtocolCachePolicy
                             timeoutInterval:5]; // 5 second timeout?

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

    if(responseString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]){
        NSLog(@"Recieved String Result: %@", responseString);
    } else {
        NSLog(@"Response String is null!");
    }
A: 

Thanks for the good suggestions. The code magically worked this morning, so I'm guessing my webserver went down or something last night.

Ben Holland