使用delegate的方式:
@interface ViewController () <NSURLConnectionDataDelegate>
/** 文件數(shù)據(jù) */
@property (nonatomic, strong) NSMutableData *fileData;
/** 文件的總長度 */
@property (nonatomic, assign) NSInteger contentLength;
@end
<NSURLConnectionDataDelegate>相關(guān)代理方法實現(xiàn):
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/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);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"下載完畢");
// 將文件寫入沙盒中
// 緩存文件夾
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
// 文件路徑
NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.mp4"];
NSLog(@"%@",file);
// 寫入數(shù)據(jù)
[self.fileData writeToFile:file atomically:YES];
self.fileData = nil;
}
如果要下載的文件足夠小:
- (void)dataDownlaod{
NSURL *url = [NSURL URLWithString:@"http://www.example.com:8080/resources/images/minion_15.png"];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
NSString *file = [caches stringByAppendingPathComponent:@"box_minion_15.png"];
[data writeToFile:file atomically:YES];
}