I am developing an iPhone application for an audio player. I want to give some options to the user so they can listen to the song/music by streaming or they can download the audio file and store in sqlite database. I know how to stream the audio files in the app programmatically. But I don’t know how to store the downloaded audio file in sqlite database using BLOB. Additionally, after storing the audio file in the sqlite DB I need to fetch the audio file and play the song. How do I fetch the audio file from sqlite DB?
This is my code for downloading the audio file.
NSURL *url = [NSURL URLWithString:@"http://www.fileurl.com/example.mp3"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDownloadDestinationPath:[NSString stringWithFormat:@"%@",dataPath]];
[request setDelegate:self];
[request startAsynchronous];
I don't recommend to store binary files in database as blobs.
it will make you a problem with growing database file size in future. You will have to implement smart vacuum operation which is very slow on large data amounts.
My strong opinion: the files must be stored in file system. Store your file in application Documents folder and store a kind of link to them in database.
you can download file and write audio file using NSDocumentDirectory in app. Documents folder like
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"audio.mp3"]];
[{your audio file in NSData} writeToFile:path atomically:YES];
now store only "audio.mp3" in database
when you retrieve data from database that give you name like
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:{database store name}]];
note if you store full path that not working because Documents foldar path change whenever you run app.