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

但是,我在网上阅读,如果我想添加一个超时,我应该使用NSURLRequest。第一个代码工作正常,但第二个代码总是返回@“”(不是零,只是“”)。任何人有任何建议?什么是使用NSURLRequest的stringWithContentsOfURL的equivlent代码?

我也读了NSURLConnection的需要其他类型的web压缩的可能,而的NSURLRequest做将无法处理的照顾,所以我想我最好只是去更圆润的解决方案。 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!"); 
    } 
+0

你试过检查错误吗?如果连接出现问题,那么它可能有一个值。 – skorulis 2010-10-26 04:17:03

+0

我建议你去进行异步网络调用,而不是使用sendSynchrounousRequest。这是一个更多的代码来编写,但它可以避免不必执行线程操作,从而避免锁定主线程。作为奖励,它也可以取消请求。 – loomer 2010-10-26 08:33:25

+0

好主意loomer,但我仍然想把它放在另一个线程中,因为我相信如果我不这样做,它仍然会在主线程中阻塞。 – 2010-10-26 14:17:14

回答

0

感谢您的好建议。代码神奇地工作今天上午,所以我猜我的网络服务器倒了或昨晚。