标签:
// 这种方法没法暂停,只适合下载小文件 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];
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); }
标签:
原文地址:http://www.cnblogs.com/BJTUzhengli/p/5154223.html