標籤:
#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
iOS之小檔案下載