0

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?

Jimmery
  • 9,783
  • 25
  • 83
  • 157
  • a bit like this: http://stackoverflow.com/questions/6238139/ios-download-and-save-image-inside-app but with mp3's and asynchronously – Jimmery Mar 18 '15 at 14:48

2 Answers2

7

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];
Marcos Crispino
  • 8,018
  • 5
  • 41
  • 59
5

The most modern way is to use NSURLSession. It had built in download functionality. Use an NSURLSessionDownloadTask for this.

Swift

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];
Rengers
  • 14,911
  • 1
  • 36
  • 54