【问题标题】:iOS download an mp3 to use later on in an app [duplicate]iOS下载一个mp3以供以后在应用程序中使用[重复]
【发布时间】:2015-05-21 10:03:01
【问题描述】:
我是否可以从网站下载 mp3,以便稍后在我的应用中使用它,而不会阻止我应用的其余部分执行?
我一直在寻找的只是同步的方法。
我想将 mp3 缓存在一个数组中。我最多只能得到 5 或 6 个短片。
谁能帮忙?
【问题讨论】:
标签:
ios
iphone
ipad
cocoa-touch
【解决方案1】:
最现代的方法是使用 NSURLSession。它内置了下载功能。为此使用NSURLSessionDownloadTask。
斯威夫特
let url = NSURL(string:"http://example.com/file.mp3")!
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { fileURL, response, error in
// fileURL is the URL of the downloaded file in a temporary location.
// You must move this to a location of your choosing
}
task.resume()
Objective-C
NSURL *url = [NSURL URLWithString:@"http://example.com/file.mp3"];
NSURLSessionDownloadTask *task = [[NSURLSession sharedSession] downloadTaskWithURL:url completionHandler:^(NSURL *fileURL, NSURLResponse *response, NSError *error) {
// fileURL is the URL of the downloaded file in a temporary location.
// You must move this to a location of your choosing
}];
[task resume];
【解决方案2】:
是的,你可以。
您可以使用NSURLConnection 并将接收到的数据保存到临时 NSData 变量中,完成后将其写入磁盘。
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
_mutableData = [NSMutableData new];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
if (_mutableData) {
[_mutableData appendData:data];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
dispatch_queue_t bgGlobalQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(bgGlobalQueue, {
[_mutableData writeToFile:_filePath atomically:YES];
});
}
注意:您应该将所有相应的错误处理添加到上述代码中,不要“按原样”使用它。
然后,您可以使用文件路径创建NSURL,并使用该 URL 播放 mp3 文件。
NSURL *url = [NSURL fileURLWithPath:_filePath];