通过NSURLConnection进行异步下载
NSURLConnection提供了两种方式来实现连接,一种是同步的,另一种是异步的,异步的连接会创建一个新的线程,这个线程将会来负责下载的动作。而对于同步连接,在下载链接和处理通讯时,则会阻塞当前调用线程。
许多开发者都会认为同步的连接将会堵塞主线程,其实这种观点是错误的。一个同步的连接是会阻塞调用它的进程。如果你在主线程中创建一个同步连接,主线程会阻塞。但是如果你并不是从主线程开启的一个同步的连接,它将会类似异步的连接一样。因此这种情况并不会堵塞你的主线程。事实上,同步和异步的主要区别就是运行runtime会为异步连接创建一个线程,而同步连接则不会。
//asynchronousRequest connection
- (void)fetchAppleHtml {
NSString*urlString=@"http://www.apple.com";
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*relquest = [NSURLRequestrequestWithURL:urlcachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheDatatimeoutInterval:30.0f];
NSOperationQueue*queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:relquestqueue:queuecompletionHandler:^(NSURLResponse*_Nullableresponse,NSData*_Nullabledata,NSError*_NullableconnectionError) {
if([datalength] >0&& connectionError ==nil) {
//请求到数据并且没有错误
//获取沙盒目录
NSString*documentsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES)objectAtIndex:0];
//创建文件路径
//stringByAppendingPathComponent和stringByAppendingString区别拼接地址时候stringByAppendingPathComponent自动拼接“/”
NSString*filePath = [documentsDirstringByAppendingPathComponent:@"apple.html"];
[datawriteToFile:filePathatomically:YES];
NSLog(@"Successfully saved the file to %@",filePath);
NSString*html = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
//NSLog(@"HTML = %@",html);
}elseif([datalength] ==0&& connectionError ==nil) {
NSLog(@"Nothing was downloaded");
}elseif(connectionError !=nil) {
NSLog(@"Error happend = %@",connectionError);
}
}];
}
通过NSURLConnection进行同步下载
使用NSURLConnection的sendSynchronousRequest:returningResponse:error:类方法,我们可以进行同步请求。在创建一个同步的网络连接的时候我们需要明白一点,并不是是我们的这个同步连接一定会堵塞我们的主线程,如果这个同步的连接是创建在主线程上的,那么这种情况下是会堵塞我们的主线程的,其他的情况下是不一定会堵塞我们的主线程的。如果你在GCD的全局并发队列上初始化了一个同步的连接,你其实并不会堵塞我们的主线程的。
我们来初始化第一个同步连接,并看看会发生什么。在实例中,我们将尝试获取Yahoo!美国站点主页内容:
- (void)fetchYahooData {
NSLog(@"We are here...");
NSString*urlString =@"http://www.yahoo.com";
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*request = [NSURLRequestrequestWithURL:url];
NSURLResponse*response =nil;
NSError*error =nil;
NSLog(@"Firing synchronous url connection...");
NSData*data = [NSURLConnectionsendSynchronousRequest:requestreturningResponse:&responseerror:&error];
if([datalength] >0&& error ==nil) {
NSLog(@"%lu bytes of data was retured.",(unsignedlong)[datalength]);
}elseif([datalength] ==0&& error ==nil) {
NSLog(@"NO data was returned");
}elseif(error !=nil) {
NSLog(@"Error happened = %@",error);
}
NSLog(@"We are done");
}
//call sendSynchronousRequest on GCD pool
- (void)fetchYahooData2_GCD {
NSLog(@"We are here...");
NSString*urlString =@"http://www.yahoo.com";
NSLog(@"Firing synchronous url connection...");
dispatch_queue_tdispatchQueue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
dispatch_async(dispatchQueue , ^{
NSURL*url = [NSURLURLWithString:urlString];
NSURLRequest*urlRequest = [NSURLRequestrequestWithURL:url];
NSURLResponse*response =nil;
NSError*error =nil;
NSData*data = [NSURLConnectionsendSynchronousRequest:urlRequestreturningResponse:&responseerror:&error];
if([datalength] >0&& error ==nil) {
NSLog(@"%lu bytes of data was returned.",(unsignedlong)[datalength]);
}elseif([datalength] ==0&& error ==nil){
NSLog(@"No data was returned.");
}elseif(error !=nil){
NSLog(@"Error happened = %@",error);
}
});
NSLog(@"We are done.");
}
通过NSURLConnection发送一个HTTP GET请求
- (void)httpGetWithParams {
NSString*urlString =@"http://chaoyuan.sinaapp.com";
urlString = [urlStringstringByAppendingString:@"?p=1059"];
NSURL*url = [NSURLURLWithString:urlString];
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
[requestsetTimeoutInterval:30.0f];
[requestsetHTTPMethod:@"Get"];
NSOperation*queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*_Nullableresponse,NSData*_Nullabledata,NSError*_NullableconnectionError) {
if([datalength] >0&& connectionError ==nil) {
NSString*html = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"html = %@",html);
}elseif([datalength] ==0&& connectionError ==nil) {
NSLog(@"nothing was downloaded.");
}elseif(connectionError !=nil) {
NSLog(@"Error happened = %@",connectionError);
}
}];
}
通过NSURLConnection发送一个HTTP POST请求
//send a POST request to a server with some params
- (void)httpPostWithParams {
NSString*urlString =@"http://chaoyuan.sinaapp.com";
urlString = [urlStringstringByAppendingString:@"?param1=First"];
urlString = [urlStringstringByAppendingString:@"¶m2=Second"];
NSURL*url = [NSURLURLWithString:urlString];
NSMutableURLRequest*request = [NSMutableURLRequestrequestWithURL:url];
[requestsetTimeoutInterval:30.0f];
[requestsetHTTPMethod:@"POST"];
NSString*body =@"bodyParam1=BodyValue1&bodyParam2=BodyValue2";
[requestsetHTTPBody:[bodydataUsingEncoding:NSUTF8StringEncoding]];
NSOperation*queue = [[NSOperationQueuealloc]init];
[NSURLConnectionsendAsynchronousRequest:requestqueue:queuecompletionHandler:^(NSURLResponse*_Nullableresponse,NSData*_Nullabledata,NSError*_NullableconnectionError) {
if([datalength] >0&& connectionError ==nil) {
NSString*html = [[NSStringalloc]initWithData:dataencoding:NSUTF8StringEncoding];
NSLog(@"html = %@",html);
}elseif([datalength] ==0&& connectionError ==nil) {
NSLog(@"nothing was downloaded.");
}elseif(connectionError !=nil) {
NSLog(@"Error happened = %@",connectionError);
}
}];
}