当时我们创建一个异步的请求的时候,你想设置一个响应超时的值,来完善你的应用程序。设置一下传递给 NSURLConnection 类的参数 URL 请求超时属性。当初始化 NSURLRequest 这个对象,并且把这个对象传递给 URL 连接对象的时候,你可以使用requestWithURL:cachePolicy:timeoutInterval:这个类方法,将超时的值传递给 timeoutInterval 参数。
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest =
[NSURLRequest
requestWithURL:url cachePolicy:NSURLRequestReloadIgnori
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);
}
}];