iOS下载mp3,以便以后在应用程序中使用

iOS下载mp3,以便以后在应用程序中使用,ios,iphone,ipad,cocoa-touch,Ios,Iphone,Ipad,Cocoa Touch,我是否可以从网站下载mp3,以便以后在我的应用程序中使用它,而不阻止应用程序其余部分的执行 我一直在寻找同步的方法 我想在阵列中缓存mp3。我最多只能得到5到6个短片 有人能帮忙吗?是的,你能 您可以使用NSURLConnection并将收到的数据保存到临时NSData变量中,完成后将其写入磁盘 - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { _

我是否可以从网站下载mp3,以便以后在我的应用程序中使用它,而不阻止应用程序其余部分的执行

我一直在寻找同步的方法

我想在阵列中缓存mp3。我最多只能得到5到6个短片

有人能帮忙吗?

是的,你能

您可以使用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];

最现代的方法是使用NSURLSession。它内置了下载功能。为此使用NSURLSessionDownloadTask

迅捷的

目标-C

有点像这样:但是使用mp3和异步
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()
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];