Jim*_*ery 0 iphone cocoa-touch ipad ios
我可以从网站上下载一个mp3,这样我以后可以在我的应用程序中使用它,而不会阻止我应用程序执行的其余部分吗?
我一直在寻找的是同步方式.
我想将mp3缓存在一个数组中.我最多只能获得5或6个短片.
有人可以帮忙吗?
是的你可以.
您可以使用a 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];
});
}
Run Code Online (Sandbox Code Playgroud)
注意:您应该将所有相应的错误处理添加到上面的代码中,不要"按原样"使用它.
然后,您可以NSURL使用文件路径创建一个并使用该URL播放mp3文件.
NSURL *url = [NSURL fileURLWithPath:_filePath];
Run Code Online (Sandbox Code Playgroud)
最现代的方法是使用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()
Run Code Online (Sandbox Code Playgroud)
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];
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1301 次 |
| 最近记录: |