开发者

What's the equivlent code for stringWithContentsOfURL using a NSURLRequest?

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!");
    }


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜