【问题标题】:Adding A TimeOut? [duplicate]添加超时? [复制]
【发布时间】:2011-11-30 03:16:47
【问题描述】:

可能重复:
NSURLConnection timeout?

我有这个代码:

NSURL *url = [NSURL URLWithString:@"http://some-url-that-has-to-work/"];
    NSURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    NSHTTPURLResponse *response = nil;
    [NSURLConnection sendSynchronousRequest:request
        returningResponse:&response error:NULL];
    return (response != nil);

有没有办法添加超时,所以如果请求超过 1 分钟,它就会超时?

【问题讨论】:

    标签: iphone objective-c ios4 xcode4


    【解决方案1】:

    我建议你试试ASIHTTPRequest。它是 iOS 通用网络连接的包装器。它拥有您需要的一切,包括超时和失败时的多次连接尝试。 http://allseeing-i.com/ASIHTTPRequest/

    您可以这样设置全局超时:

       [ASIHTTPRequest setDefaultTimeOutSeconds:5];
    

    然后调用网址:

    NSURL *url = [NSURL URLWithString:@"http://www......."];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
    [request setDelegate:self];
    [request startAsynchronous];
    

    您拥有可以在超时(或响应)时使用的委托函数

    - (void)requestFinished:(ASIHTTPRequest *)request {
    // this is called if the request is successful
    }
    
    - (void)requestFailed:(ASIHTTPRequest *)request {
    // this is called if the request fails
    }
    

    【讨论】:

    • ASI 是为了在 NSURLConnection 正常工作时能够设置超时策略而添加到您的项目中。
    • @aporat 切换到ASIHTTPRequest 只是为了设置超时没有意义。事实上底层 ASIHTTPRequest 是 NSURLConnection !
    猜你喜欢
    • 2021-02-25
    • 1970-01-01
    • 2011-07-16
    • 2015-10-22
    • 2014-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多