iOS download mp3 to use later in an app

advertisements

This question already has an answer here:

  • Xcode: Download mp3 file [closed] 1 answer

Is it possible for me to download an mp3 from a website so I can use it later on in my app, without blocking the rest of my app's execution?

All I keep finding are synchronous ways of doing this.

I would like to cache the mp3's in an array. I will only be getting 5 or 6 short clips at the most.

Can anyone help?


Yes, you can.

You can use a NSURLConnection and save the received data into a temporary NSData variable, and when done, write it to disk.

- (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];
    });
}

Note: you should add all the corresponding error handling to the above code, do not use it "as is".

You can then create a NSURL with the file path and use that URL to play the mp3 file.

NSURL *url = [NSURL fileURLWithPath:_filePath];