1 // 2 // ViewController.m 3 // 05-backgroudDownload 4 // 5 6 #import "ViewController.h" 7 8 @interface ViewController () <NSURLSessionDownloadDelegate> 9 10 @end 11 12 @implementation ViewController 13 14 - (void)viewDidLoad { 15 [super viewDidLoad]; 16 // Do any additional setup after loading the view, typically from a nib. 17 18 NSURL *url = [NSURL URLWithString:@"http://218.76.27.57:8080/chinaschool_rs02/135275/153903/160861/160867/1370744550357.mp3"]; 19 20 //创建后台配置 21 // NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"backdownloadTask"]; 22 NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration]; 23 24 //根据配置对象来创建后台Session 25 NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]]; 26 27 28 NSURLSessionDownloadTask *downloadTask = [session downloadTaskWithURL:url]; 29 30 [downloadTask resume]; 31 32 33 34 } 35 36 - (void)moveDownloadFile:(NSURL *)location ToPath:(NSString *)targetFilePath { 37 38 //目标路径 39 NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:targetFilePath]; 40 41 NSFileManager *manager = [NSFileManager defaultManager]; 42 43 //判断目标路径下的文件是否存在,如果不存在,则剪切 44 BOOL exist = [manager fileExistsAtPath:filePath]; 45 if (!exist) { 46 47 [manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:nil]; 48 } 49 50 NSLog(@"文件保存成功"); 51 52 53 } 54 55 - (void)didReceiveMemoryWarning { 56 [super didReceiveMemoryWarning]; 57 // Dispose of any resources that can be recreated. 58 } 59 60 61 #pragma mark - NSURLSessionDownloadDelegate 62 63 //下载完成时调用 64 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 65 didFinishDownloadingToURL:(NSURL *)location { 66 67 NSLog(@"location:%@", location); 68 69 70 //把临时目录下的文件剪切到目标文件夹。 71 [self moveDownloadFile:location ToPath:@"Documents/jay.mp3"]; 72 73 74 } 75 76 //监听下载进度,此协议方法可能会被调用多次 77 /* 78 bytesWritten:本次传输下载了多少字节 79 totalBytesWritten:已经下载了多少字节 80 totalBytesExpectedToWrite:文件的总大小 81 82 */ 83 - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 84 didWriteData:(int64_t)bytesWritten 85 totalBytesWritten:(int64_t)totalBytesWritten 86 totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite { 87 88 float progress = (float)totalBytesWritten / totalBytesExpectedToWrite; 89 90 NSLog(@"下载%.2f%%", progress * 100); 91 92 93 } 94 95 96 @end
时间: 2024-10-07 20:00:50