I am creating an application in which the user can select a song on the settings tab and play it in another view upon request. I want this element to be saved if the user needs to close the application and reopen it at another time.
I managed to allow the user to select and store the song with:
-(IBAction)showMediaPicker:(id)sender{ MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeAny]; mediaPicker.delegate = self; mediaPicker.allowsPickingMultipleItems = NO; mediaPicker.prompt = @"Select Alarm Sound"; [self presentModalViewController:mediaPicker animated:YES]; } - (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection { [self dismissModalViewControllerAnimated: YES]; settingsData.selectedSong = mediaItemCollection;
but I want the user to have to do this every time they use the application.
I tried using NSUserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:settingsData.selectedSong forKey:@"alarmSoundKey"]; [defaults synchronize];
but get the error:
* - [NSUserDefaults setObject: forKey:]: attempt to insert the value of the non-property '' of the class 'MPMediaItemCollection'. Note that dictionaries and arrays in property lists should also contain only property values.
What are my options please? Not quite sure how to handle this ...
DECISION -
I can not answer my questions, so I will put it here:
I FOUND MY OWN SOLUTION:
First convert / encode MPMediaItemCollection to an NSData object and slam save it with NSUserDefaults using:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:mediaItemCollection]; NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; [defaults setObject:data forKey:@"someKey"]; [defaults synchronize];
From there you can decode and use elsewhere in your application ....
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSData *data = [defaults objectForKey:@"someKey"]; MPMediaItemCollection *mediaItemCollection = [NSKeyedUnarchiver unarchiveObjectWithData:data]
Hope this is some help to someone. Spread the word, it's not covered enough. Literally worked on this problem for about 4 hours ...