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

来源:互联网 发布:阿里云服务器租用费用 编辑:程序博客网 时间:2024/05/29 09:22

    当时我们创建一个异步的请求的时候,你想设置一个响应超时的值,来完善你的应用程序。设置一下传递给 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);
}
}]; 

原创粉丝点击