网编基础(4)网络下载音乐和视频

时间:2022-04-22 15:54:25

网编基础(4)网络下载音乐和视频

代码正文:


#import "ViewController.h"

@interface ViewController ()<NSURLSessionDownloadDelegate>
{
NSURLSessionDownloadTask *task;
NSURLSession *session;
NSData *savedData;

}
@property (weak, nonatomic) IBOutlet UIProgressView *progressBar;
@end

@implementation ViewController

- (void)viewDidLoad {
[super viewDidLoad];
}

- (IBAction)downloadURLMp3:(UIButton *)sender {

//创建URL
NSURL *url = [NSURL URLWithString:@"http://www.itinge.com/music/3/9158.mp3"];

//创建网络请求
NSURLRequest *request = [NSURLRequest requestWithURL:url];

//创建网络会话
session = [NSURLSession sharedSession];

//创建网络会话加载任务
task = [session downloadTaskWithRequest:request completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

//文件管理创建
NSFileManager *manager = [NSFileManager defaultManager];
//拼接本地沙盒路径存储地址
NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/music.mp3"];
//将下载的文件保存到本地路径
[manager moveItemAtURL:location toURL:[NSURL fileURLWithPath:filePath] error:NULL];

if (error) {

NSLog(@"下载歌曲出现错误");
}else {

NSLog(@"歌曲下载成功");
}


}];

//发起网络请求
[task resume];

}
- (IBAction)downloadURLMp4:(UIButton *)sender {

//创建URL
NSURL *url = [NSURL URLWithString:@"http://vf1.mtime.cn/Video/2012/04/23/mp4/120423212602431929.mp4"];

//创建网络请求
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

//创建网络会话配置对象
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

//创建网络会话
session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[NSOperationQueue mainQueue]];

//创建网络会话任务对象
task = [session downloadTaskWithRequest:request];

//发起网络请求
[task resume];

}
//开始下载就调用(不断的调用)
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
/*
这个方法在下载的时候不断的调用
bytesWritten:本次传输下载了多少个字节
totalBytesWritten:目前已经下载了多少个字节
totalBytesExpectedToWrite:文件的总大小
*/


//获取下载的百分比,计算进度条的值
CGFloat myValue = totalBytesWritten/(CGFloat)totalBytesExpectedToWrite;
_progressBar.progress = myValue;



}
- (IBAction)pauseAction:(UIButton *)sender {

//取消的时候,保存数据
[task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {

savedData = resumeData;

task = nil;

}];

}
- (IBAction)continueAction:(UIButton *)sender {

//点击继续按钮,将暂停的时候保存的数据恢复下载
task = [session downloadTaskWithResumeData:savedData];

//再次发起网络请求
[task resume];
}

- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {

NSLog(@"%@", location);
NSLog(@"下载成功");
}

@end