1. 下载图片
注意:这是同步,在当前线程执行
2. 使用系统的网络请求方法
//1.图片的url
NSURL * url = [NSURL URLWithString: @"imageURL"];
//2.下载二进制数据
NSData * data = [NSData dataWithContentsOfURL: url];
//3.转换
UIImage * image = [UIImage imageWithData: data];
3. 使用代理下载小文件
//1.url
NSURL * url = [NSURL URLWithString: @"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest * request = [NSURLRequest requestWithURL: url];
//3.发送请求
[NSURLConnection sendAsynchronousRequest: request queue: [NSOperationQueue mainQueue] completionHandler: ^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
//4.写数据到沙盒中
NSString * fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent: @"123.mp4"]; [data writeToFile: fullPath atomically: YES];
}];
//存在的问题:
//1.无法监听进度
//2.内存飙升
// 添加属性,记录进度
@property (nonatomic, strong) NSMutableData *fileData;
@property (nonatomic, assign) NSInteger totalSize;
//注意初始化可变data,可使用懒加载
-(NSMutableData *)fileData
{
if (_fileData == nil) {
_fileData = [NSMutableData data];
}
return _fileData;
}
-(void)download3
{
//1.url
// NSURL *url = [NSURL URLWithString:@"http://imgsrc.baidu.com/forum/w=580/sign=54a8cc6f728b4710ce2ffdc4f3cec3b2/d143ad4bd11373f06c0b5bd1a40f4bfbfbed0443.jpg"];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_01.mp4"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.发送请求 遵守代理 NSURLConnectionDataDelegate
[[NSURLConnection alloc]initWithRequest:request delegate:self];
}
#pragma mark ----------------------
#pragma mark NSURLConnectionDataDelegate
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
//得到文件的总大小(本次请求的文件数据的总大小)
self.totalSize = response.expectedContentLength;
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// NSLog(@"%zd",data.length);
[self.fileData appendData:data];
//进度=已经下载/文件的总大小
NSLog(@"%f",1.0 * self.fileData.length /self.totalSize);
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//4.写数据到沙盒中
NSString *fullPath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]stringByAppendingPathComponent:@"123.mp4"];
[self.fileData writeToFile:fullPath atomically:YES];
NSLog(@"%@",fullPath);
}
来源: http://www.jianshu.com/p/97d70c923c65