IOS中处理异步连接中的超时

    当时我们创建一个异步的请求的时候,你想设置一个响应超时的值,来完善你的应用程序。设置一下传递给 NSURLConnection 类的参数 URL 请求超时属性。当初始化 NSURLRequest 这个对象,并且把这个对象传递给 URL 连接对象的时候,你可以使用requestWithURL:cachePolicy:timeoutInterval:这个类方法,将超时的值传递给 timeoutInterval 参数。

    比如,你想最大限度的等待 30 秒来同步连接下载苹果主页的内容,你将创建 URL 请求 如下: 

NSString *urlAsString = @"http://www.apple.com"; 

NSURL *url = [NSURL URLWithString:urlAsString]; 

NSURLRequest *urlRequest =
[NSURLRequest

requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0f];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[
NSURLConnection

sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data,

NSError *error) {
if ([data length] >0 &&
error == nil){
NSString *html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; 

NSLog(@"HTML = %@", html);
}
else if ([data length] == 0 &&
error == nil)

{
NSLog(@"Nothing was downloaded.");
}
else if (error != nil)

{
NSLog(@"Error happened = %@", error);
}
}]; 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值