路徑的拼接問題
1. stringByAppendingString (是在后面加后綴的意思)
在模擬器上好用,真機上提示無法進行操作,改成第二種寫法即可.
2.stringByAppendingPathComponent(是在后面加上“/”號連接 讓它成為完整的路徑)
路徑拼接.png
附上下載代碼:(協(xié)議可以改成block)
// 1. 建立請求
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:model.music_url]];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
// 下載 存儲路徑
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingString:model.path];
operation.outputStream = [NSOutputStream outputStreamToFileAtPath:path append:NO];
// 設(shè)置下載進程塊代碼
/*
bytesRead 當(dāng)前一次讀取的字節(jié)數(shù)(100k)
totalBytesRead 已經(jīng)下載的字節(jié)數(shù)(4.9M)
totalBytesExpectedToRead 文件總大小(5M)
*/
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
// 設(shè)置進度條的百分比
CGFloat precent = (CGFloat)totalBytesRead / totalBytesExpectedToRead;
// NSLog(@"%f", precent);
if ([self.delegate respondsToSelector:@selector(downloadMusicProgress:)]) {
[self.delegate downloadMusicProgress:precent];
}
}];
// 設(shè)置下載完成操作
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if ([self.delegate respondsToSelector:@selector(downloadMusic:success:)]) {
[self.delegate downloadMusic:model success:nil];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if ([self.delegate respondsToSelector:@selector(downloadMusic:error:)]) {
[self.delegate downloadMusic:model error:error];
}
}];
NSLog(@"加入隊列");
[_downloadQueue addOperation:operation];