作品链接:
http://www.jianshu.com/users/1e0f5e6f73f6/top_articles
- 1.第一种
NSURL *url = [NSURL URLWithString:@"图片请求路径"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.imagView.image = [UIImage imageWithData:data];
- 2.第二种 NSURLConnection
NSURL *url = [NSURL URLWithString:@"图片请求路径"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
self.imagView.image = [UIImage imageWithData:data];
- 3.下载视频 代理方法
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"请求路径"];
//2.创建请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.设置代理,发送请求
[NSURLConnection connectionWithRequest:request delegate:self];
}
pragma mark NSURLConnectionDataDelegate
声明文件数据 已下载大小和总文件大小
// 文件数据
@property (nonatomic, strong) NSMutableData *fileData;
//当前已经下载文件的大小
@property (nonatomic, assign) NSInteger currentLength;
//下载文件的总大小
@property (nonatomic, assign) NSInteger totalLength;
/*
1.接收到服务器响应的适合调用 1次
*/
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 创建data
self.fileData = [NSMutableData data];
//拿到文件的总大小
self.totalLength = response.expectedContentLength;
NSLog(@"%zd",self.totalLength);
}
/*
2.接收到服务器返回的数据,会调用多次
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接数据
[self.fileData appendData:data];
self.currentLength = self.fileData.length;
// NSLog(@"%zd---%zd",data.length,self.currentLength);
NSLog(@"%f",1.0 * self.currentLength / self.totalLength);// 此时数据是在内存中,直接退出的话,再次启动数据消失
}
/*
3.当请求完成之后调用该方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//保存下载的文件到沙河
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//拼接文件全路径
NSString *fullPath = [caches stringByAppendingPathComponent:@"XXOO.mp4"];
//写入数据到文件
[self.fileData writeToFile:fullPath atomically:YES];
NSLog(@"%@",fullPath);
// self.imagView.image = [UIImage imageWithData:self.fileData];
}
/*
4.当请求失败的适合调用该方法,如果失败那么error有值
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}