这个方法和上面的一样也只能适用于小文件的下载。
#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); }
转载于:https://www.cnblogs.com/BJTUzhengli/p/5154223.html