【问题标题】:What's the equivlent code for stringWithContentsOfURL using a NSURLRequest?使用 NSURLRequest 的 stringWithContentsOfURL 的等效代码是什么?
【发布时间】:2010-10-26 03:41:02
【问题描述】:
NSURL *url = [NSURL URLWithString:escapedUrlString];
NSString *responseString = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil]; 

但是,我在网上阅读到,如果我想添加超时,我可能应该使用 NSURLRequest。第一个代码工作正常,但第二个代码总是返回 @""(不是 nil,只是 "")。有人有什么建议吗?

我还读到 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!");
    }

【问题讨论】:

  • 你试过检查错误吗?如果连接出了问题,那么它可能有一个值。
  • 我建议您使用异步网络调用而不是使用 sendSynchrounousRequest。需要编写更多代码,但它使您不必进行线程处理以避免锁定主线程。作为奖励,它还可以取消请求。
  • 好主意 loomer,但我仍然想把它放在另一个线程中,因为我相信如果我不这样做它仍然会阻塞在主线程中。
  • 异步网络调用永远不会阻塞主线程。它们旨在这样做。

标签: objective-c networking timeout nsurlconnection nsurlrequest


【解决方案1】:

感谢您的好建议。代码今天早上神奇地工作了,所以我猜我的网络服务器昨晚出现了故障。

【讨论】:

    猜你喜欢
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-06
    • 2017-06-09
    • 1970-01-01
    • 2021-11-17
    相关资源
    最近更新 更多