#import "ViewController.h"
@interface ViewController () <NSURLConnectionDataDelegate>
@property (weak, nonatomic) IBOutlet UIProgressView *progressView;
/** 文件数据 */
@property (nonatomic, strong) NSMutableData *fileData;
/** 文件的总长度 */
@property (nonatomic, assign) NSInteger contentLength;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/videos/minion_15.mp4"];
[NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:url] delegate:self];
}
#pragma mark - <NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response
{
self.contentLength = [response.allHeaderFields[@"Content-Length"] integerValue];
self.fileData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.fileData appendData:data];
CGFloat progress = 1.0 * self.fileData.length / self.contentLength;
NSLog(@"已下载:%.2f%%", (progress) * 100);
self.progressView.progress = progress;
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"下载完毕");
// 将文件写入沙盒中
// 缓存文件夹
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 文件路径
NSString *file = [caches stringByAppendingPathComponent:@"minion_15.mp4"];
// 写入数据
[self.fileData writeToFile:file atomically:YES];
self.fileData = nil;
}
- (void)connDownload
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"];
[NSURLConnection sendAsynchronousRequest:[NSURLRequest requestWithURL:url] queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
NSLog(@"%zd", data.length);
}];
}
- (void)dataDownlaod
{
NSURL *url = [NSURL URLWithString:@"http://120.25.226.186:32812/resources/images/minion_15.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSLog(@"%zd", data.length);
}
@end