作品鏈接:
http://www.lxweimin.com/users/1e0f5e6f73f6/top_articles
- 1.第一種
NSURL *url = [NSURL URLWithString:@"圖片請(qǐng)求路徑"];
NSData *data = [NSData dataWithContentsOfURL:url];
self.imagView.image = [UIImage imageWithData:data];
- 2.第二種 NSURLConnection
NSURL *url = [NSURL URLWithString:@"圖片請(qǐng)求路徑"];
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:@"請(qǐng)求路徑"];
//2.創(chuàng)建請(qǐng)求對(duì)象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
//3.設(shè)置代理,發(fā)送請(qǐng)求
[NSURLConnection connectionWithRequest:request delegate:self];
}
pragma mark NSURLConnectionDataDelegate
聲明文件數(shù)據(jù) 已下載大小和總文件大小
// 文件數(shù)據(jù)
@property (nonatomic, strong) NSMutableData *fileData;
//當(dāng)前已經(jīng)下載文件的大小
@property (nonatomic, assign) NSInteger currentLength;
//下載文件的總大小
@property (nonatomic, assign) NSInteger totalLength;
/*
1.接收到服務(wù)器響應(yīng)的適合調(diào)用 1次
*/
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// 創(chuàng)建data
self.fileData = [NSMutableData data];
//拿到文件的總大小
self.totalLength = response.expectedContentLength;
NSLog(@"%zd",self.totalLength);
}
/*
2.接收到服務(wù)器返回的數(shù)據(jù),會(huì)調(diào)用多次
*/
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// 拼接數(shù)據(jù)
[self.fileData appendData:data];
self.currentLength = self.fileData.length;
// NSLog(@"%zd---%zd",data.length,self.currentLength);
NSLog(@"%f",1.0 * self.currentLength / self.totalLength);// 此時(shí)數(shù)據(jù)是在內(nèi)存中,直接退出的話(huà),再次啟動(dòng)數(shù)據(jù)消失
}
/*
3.當(dāng)請(qǐng)求完成之后調(diào)用該方法
*/
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"connectionDidFinishLoading");
//保存下載的文件到沙河
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//拼接文件全路徑
NSString *fullPath = [caches stringByAppendingPathComponent:@"XXOO.mp4"];
//寫(xiě)入數(shù)據(jù)到文件
[self.fileData writeToFile:fullPath atomically:YES];
NSLog(@"%@",fullPath);
// self.imagView.image = [UIImage imageWithData:self.fileData];
}
/*
4.當(dāng)請(qǐng)求失敗的適合調(diào)用該方法,如果失敗那么error有值
*/
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog(@"didFailWithError");
}