如何利用NSURLConnection 来获得网络资源?
引用书中的话
“
有使用NSURLConnection的两个方法。一个是异步的,而另一个是同步的。异步连接将创建一个新的线程并执行其下载过程在新线程。一个同步连接将阻塞调用线程且同时下载的内容。
许多开发者认为,一个同步连接阻塞主线程,但是这是不正确的。一个同步连接将始终阻止它被启动的线程。如果你从主线程的启动同步连接,是的,主线程将被阻塞。但是,如果你从一个线程在主线程之外启动同步连接,它会像一个异步连接,它不会阻止你的主线程。
实际上,同步和异步连接之间的唯一区别在于,运行时<runtime>将为异步连接创建一个线程,而它不会对一个同步连接这样做。
”
异步连接的过程:
为了创建一个异步连接,我们需要做到以下几点:1。在NSString的实例URL
2。我们的字符串转换为NSURL的一个实例。
NSString *urlAsString = @"http://www.apple.com";
NSURL *url = [NSURL URLWithString:urlAsString];
3.我们可以创建一个异步的URL连接
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
4.创建一个操作队列
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
5.把请求赋值给NSURLConnection,开始请求数据
6.请求结束后,在completionHandler闭包里接收
A. NSData *data服务器给我们的二进制数据
B.NSURLResponse *response,它封装了服务器发给我们的信息。
C.NSError *error失败后的信息
[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);
} }];
————————————————————————————————————————-——
##异步连接
1.让我们看看例子,我们尝试异步获取apple网站的HTML内容,然后打印这些内容去命令行窗口,把数据写入html文件
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];
/* Append the filename to the documents directory */
NSURL *filePath =
[[self documentsFolderUrl]
URLByAppendingPathComponent:@"apple.html"];
[data writeToURL:filePath atomically:YES];
NSLog(@"Successfully saved the file to %@", filePath);
}
else if ([data length] == 0 && error == nil){
NSLog(@"Nothing was downloaded.");
}
else if (error != nil){ NSLog(@"Error happened = %@", error);
} }];
##同步连接
1.让我们把完全相同的同步连接连接一个 global concurrent queue in GCD,这保证了程序的并发性
NSLog(@"We are here...");
NSString *urlAsString = @"http://www.yahoo.com";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(dispatchQueue, ^(void) {
NSURL *url = [NSURL URLWithString:urlAsString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest
returningResponse:&response
if ([data length] > 0 && error == nil){ NSLog(@"%lu bytes of data was returned.",
(unsigned long)[data length]);
} else if ([data length] == 0 && error == nil){
NSLog(@"No data was returned.");
}
else if (error != nil){ NSLog(@"Error happened = %@", error);
} });
##GET,POST,PUT,DEL请求
## http://example.com/?param1=value1¶m2=value2
NSString *urlAsString = @“ http://example.com/”;
urlAsString = [urlAsString stringByAppendingString:@"?param1=First"];
urlAsString = [urlAsString stringByAppendingString:@"¶m2=Second"];
NSURL *url = [NSURL URLWithString:urlAsString];
NSMutableURLRequest *urlRequest =
[NSMutableURLRequest requestWithURL:url];
[urlRequest setTimeoutInterval:30.0f];
##GET请求
[urlRequest setHTTPMethod:@"GET"];
##Post请求:提交数据
[urlRequest setHTTPMethod:@"POST"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
##Put请求:更新数据
[urlRequest setHTTPMethod:@"PUT"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
##Del请求:删除数据
[urlRequest setHTTPMethod:@"DELETE"];
NSString *body = @"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
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);
}
}];
##把内容简单分享去twitter
if ([SLComposeViewController
isAvailableForServiceType:SLServiceTypeTwitter]){
SLComposeViewController *controller =
[SLComposeViewController
composeViewControllerForServiceType:SLServiceTypeTwitter];
[controller setInitialText:@"MacBook Airs are amazingly thin!"];
[controller addImage:[UIImage imageNamed:@"MacBookAir"]];
[controller addURL:[NSURL URLWithString:@"http://www.apple.com/"]];
controller.completionHandler = ^(SLComposeViewControllerResult result){
NSLog(@"Completed");
};
[self presentViewController:controller animated:YES completion:nil];
}else{
NSLog(@"The twitter service is not available");
}
来源:oschina
链接:https://my.oschina.net/u/228991/blog/215044