2016 - 1 - 23 小文件下载
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了2016 - 1 - 23 小文件下载相关的知识,希望对你有一定的参考价值。
一: 使用NSData直接下载:
// 这种方法没法暂停,只适合下载小文件 NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ]; NSData *data = [NSData dataWithContentsOfURL:url options:kNilOptions error:nil]; UIImage *image = [UIImage imageWithData:data]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(0, 0, 200, 200); [self.view addSubview:imageView];
二: 使用NSURLConnect
NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png" ]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) { UIImage *image = [UIImage imageWithData:data]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.frame = CGRectMake(0, 0, 200, 200); [self.view addSubview:imageView]; }]; }
三: 采用拼接代理的方法下载
这个方法和上面的一样也只能适用于小文件的下载。
#import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelegate> @property (nonatomic, strong) NSMutableData *fileData; @property (nonatomic, assign) NSInteger contentLength; //@property (nonatomic, strong) UIImage *image; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // 这种方法没法暂停,只适合下载小文件 NSURL *url = [[NSURL alloc] initWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4" ]; NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url]; // 设置connect的代理 [NSURLConnection connectionWithRequest:request delegate:self]; } #pragma mark - NSURLConnect 的代理 // connection接收到响应,此时应当创建数据准备拼接data - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response { NSHTTPURLResponse *newResponse = response; // 获得文件的总长度 self.contentLength = [newResponse.allHeaderFields[@"Content-Length"] integerValue]; self.fileData = [NSMutableData data]; } // 接收到了数据,这个方法会被多次调用,需要在这里拼接数据 - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.fileData appendData:data]; CGFloat per = (1.0 * self.fileData.length / self.contentLength); NSLog(@"%f",per); } // 下载完成 - (void)connectionDidFinishLoading:(NSURLConnection *)connection { NSLog(@"%zd",self.fileData.length); }
以上是关于2016 - 1 - 23 小文件下载的主要内容,如果未能解决你的问题,请参考以下文章