OC下载网络数据简介
同步下载
从网络上获取数据,有如下几种方式:
//百度首页
#define BAIDU_URL @"http://www.baidu.com"
//图片地址
#define IMAGE_URL @"http://h.hiphotos.baidu.com/image/pic/item/5243fbf2b211931327b006b267380cd790238dc5.jpg"
// 请求字符串内容
NSURL * url = [NSURL URLWithString:BAIDU_URL];
NSString * strHtml = [[NSString alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding error:nil];
// 从网络上请求图片数据
NSURL * imgUrl = [NSURL URLWithString:IMAGE_URL];
NSData * data = [NSData dataWithContentsOfURL:imgUrl];
异步下载
代理方式
NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:IMAGE_URL]];
// 通过设置代理回调方法,实现获取下载数据状态的值
[NSURLConnection connectionWithRequest:req delegate:self];
#pragma mark- NSURLConnectionDelegate 代理的相关方法
// 下载数据前
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"文件大小%lld byte, 文件名字: %@", response.expectedContentLength, response.suggestedFilename);
NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response;
NSLog(@"状态码:%ld", httpResponse.statusCode);
// 清空收到的数据
self.revData.length = 0;
// 设置状态栏下的网络请求状态
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
}
// 正在下载中
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSLog(@"追加字节数目:%ld", data.length);
[self.revData appendData:data];
}
// 下载完成后
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"下载完成,收到的字节总数: %ld", self.revData.length);
NSString * savePath = @"/Users/qf/Desktop/1.jpg";
[self.revData writeToFile:savePath atomically:YES];
// 设置状态栏下的网络请求状态
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
}
block回调
NSURLRequest * req = [NSURLRequest requestWithURL:[NSURL URLWithString:IMAGE_URL]];
// 通过线程中主队列来辅助发送请求,下载完成之后即可获取整个数据的内容
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
if (connectionError) {
NSLog(@"%@", connectionError);
return ;
}
NSString * savePath = [NSHomeDirectory() stringByAppendingString:@"/Documents/1.jpg"];
NSLog(@"savePath: %@", savePath);
[data writeToFile:savePath atomically:YES];
NSLog(@"下载完成!");
}];
SDWebImage 图像缓存库
简要使用方法如下。详细文档请参考 资源文件夹中 SDWebImage/README.md
#import "UIImageView+WebCache.h"
[cell.imageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
遇到问题
工程配置
App Transport Security has blocked a cleartext HTTP (http://) resource load since it is insecure. Temporary exceptions can be configured via your app's Info.plist file.
【解决办法】
在工程文件 Info.plist中
添加 NSAppTransportSecurity 类型 Dictionary ;
在 NSAppTransportSecurity 下,
添加 NSAllowsArbitraryLoads 类型Boolean ,值设为 YES;