How do you use MPMediaItemPropertyPersistentID to play music in iPhone Music Player Framework? - ios4

My code sucessfully catalogs song names and ID's for my the entire music library. However, it will not actually play a song using this methodology and the console displays the following:
Message playbackState timed out.
Message nowPlayingItem timed out.
self.musicPlayer = [MPMusicPlayerController applicationMusicPlayer];
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongName = [[NSMutableArray alloc] init];
SongItem = [[NSMutableArray alloc] init];
NSString *songTitle;
NSString *songID;
//Collect names & ID for entire music library & put into arrays
for (MPMediaItem *song in itemsFromGenericQuery) {
songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
[SongName addObject:songTitle];
songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
[SongItem addObject:songID];
}
NSLog (#"%#", [SongName objectAtIndex:1]);
NSLog (#"%#", [SongItem objectAtIndex:1]);
// Play the second song in the list
MPMediaItemCollection *collection = [MPMediaItemCollection collectionWithItems:[NSArray arrayWithObject:[SongItem objectAtIndex:1]]];
[self.musicPlayer setQueueWithItemCollection:collection];
[self.musicPlayer play];

Once again, I'll answer my own question. The issue was that collectionWithItems: expects an array of MPMediaItems, not an array of MPMediaItemPropertyPersistentIDs. Here is the working code for anyone who may have the same problem:
MPMediaQuery *everything = [[MPMediaQuery alloc] init];
NSArray *itemsFromGenericQuery = [everything items];
SongItem = [[NSMutableArray alloc] init];
for (MPMediaItem *song in itemsFromGenericQuery) {
NSString *songTitle = [song valueForProperty: MPMediaItemPropertyTitle];
//NSLog (#”%#”, songTitle);
songID = [song valueForProperty: MPMediaItemPropertyPersistentID];
//NSLog (#”%#”, songID);
[SongItem addObject:songID];
}
//Choose the first indexed song
NSString *selectedTitle = [SongItem objectAtIndex:0];
//Use the MPMediaItemPropertyPersistentID to play the song
MPMediaPropertyPredicate *predicate = [MPMediaPropertyPredicate predicateWithValue:selectedTitle forProperty:MPMediaItemPropertyPersistentID];
MPMediaQuery *mySongQuery = [[MPMediaQuery alloc] init];
[mySongQuery addFilterPredicate: predicate];
[musicPlayer setQueueWithQuery:mySongQuery];
[musicPlayer play];

Related

Core Data input fetches into labels

I want to store data from a text field. And then use this data to populate the text in a label inside a view controller. Is this possible? Ive messed around with it, but nothing seems to work. Any thoughts? Here are my two methods...
- (IBAction)saveButton:(id)sender {
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSManagedObject *noteEntry = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
[noteEntry setValue:_notesField.text forKey:#"notes"];
NSError *error = nil;
// Save the object to persistent store
if (![coreDataStack.managedObjectContext save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
[coreDataStack saveContext];
}
Here is my view did load method:
- (void)viewDidLoad
{
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
Notes *entry = [NSEntityDescription insertNewObjectForEntityForName:#"Notes" inManagedObjectContext:coreDataStack.managedObjectContext];
_outputLabel.text = entry.notes;
}
Your code in the saveButton: method seems OK. But your code in the viewDidLoad method seems wrong. Are you trying to do the following?
- (void)viewDidLoad {
[super viewDidLoad];
CoreDataStack *coreDataStack = [CoreDataStack defaultStack];
//First way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
//Second way to init your fetchRequest:
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Notes" inManagedObjectContext:coreDataStack];
[fetchRequest setEntity:entity];
//Having a NSEntityDescription object can be usefull if you need to group your data, for example
//Set some predicates, if necessary
//Set some sortdescriptors, if necessary
NSError *error;
NSArray *resultsArray = [coreDataStack executeFetchRequest:request error:&error];
NSLog(#"%#", resultsArray);
_outputLabel.text = [[resultsArray firstObject] notes]; //if your array can only have one object
}
The NSLog will give you the structure of your fetch array (I can't guess it). You will then be able to set _outputLabel.text.
Answer by #user1966109 is exactly correct answer what you are looking for. Since you need to show the text in a label and for that you need to set predicate to get a single row. Set the predicate as below
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"value == abc"];//considerin abc is the word you are looking for.
request.predicate = predicate;
//then execute the query.

Core Data: Not saving

I'm having trouble saving to one variable letsMeet.startTimeLabel. Right after selecting NSLog shows the correct Value, however, after I save to another variable (letsMeet.endTimeLabel), letsMeet.startTimeLabel changes to (NULL). Below is the code:
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
switch (actionSheet.tag)
{
case 1:
{
if (buttonIndex == 0)
{
UIDatePicker *startDatePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag1];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"dd"];
NSDate *selectedDate = [startDatePicker date];
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:#"EEEE"];
NSDate *selectedDay= [startDatePicker date];
NSDateFormatter *monthFormatter = [[NSDateFormatter alloc] init];
[monthFormatter setDateFormat:#"MMMM"];
NSDate *selectedMonth = [startDatePicker date];
NSString *date = [[NSString alloc] initWithFormat:#"%#", [dateFormatter stringFromDate:selectedDate]];
DateLabel.text = date;
[letsMeet setDateLabel:date];
NSString *month = [[NSString alloc] initWithFormat:#"%#", [dayFormatter stringFromDate:selectedMonth]];
MonthLabel.text = month;
[letsMeet setMonthLabel:month];
NSString *day = [[NSString alloc] initWithFormat:#"%#", [monthFormatter stringFromDate:selectedDay]];
DayLabel.text = day;
[letsMeet setDateLabel:day];
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat: #"h:mm a"];
NSDate *selectedStartTime = [startDatePicker date];
NSString *startTime = [[NSString alloc] initWithFormat:#"%#", [timeFormatter stringFromDate:selectedStartTime]];
StartTimeLabel.text = startTime;
[letsMeet setStartTimeLabel:startTime];
NSError *error = nil;
if (![managedObjectContext save:&error]){
NSLog(#"Error Saving");
}
}
NSLog (#"This is the StartTime after selecting %#", letsMeet.startTimeLabel);
}
break;
case 2:
{
if (buttonIndex == 0)
{
UIDatePicker *endTimePicker = (UIDatePicker *)[actionSheet viewWithTag:kDatePickerTag2];
NSDateFormatter *endTimeFormatter = [[NSDateFormatter alloc] init];
[endTimeFormatter setDateFormat: #"h:mm a"];
NSDate *endSelectedTime = [endTimePicker date];
NSString *endTime = [[NSString alloc] initWithFormat:#"%#", [endTimeFormatter stringFromDate:endSelectedTime]];
EndTimeLabel.text = endTime;
[letsMeet setEndTimeLabel:endTime];
NSLog (#"This is the EndTime %#", letsMeet.endTimeLabel);
NSLog (#"This is the StartTime after selecting BOTH %#", letsMeet.startTimeLabel);
}
else if (buttonIndex == 1)
{
EndTimeLabel.text = #"Whenever";
[letsMeet setEndTimeLabel:EndTimeLabel.text];
}
NSError *error = nil;
if (![managedObjectContext save:&error]) {
}
}break;
// Handle the error.
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
UIViewController *destinationViewController = segue.destinationViewController;
NSLog (#"Prepare For Segue StartTime %#", letsMeet.startTimeLabel);
NSLog (#"Prepare For Segue EndTime%#", letsMeet.endTimeLabel);
}
Here is the log:
2013-02-20 21:38:24.253 AppointmentTime[3129:c07] This is the StartTime after selecting 9:30 AM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the EndTime 12:15 PM
2013-02-20 21:38:32.325 AppointmentTime[3129:c07] This is the StartTime after Selecting BOTH (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue StartTime (null)
2013-02-20 21:38:34.069 AppointmentTime[3129:c07] Prepare For Segue EndTime12:15 PM
Q: Why would letsMeet.startTimeLabel show up correct the first time and after selecting EndTime, it changes to NULL. Please note EndTime continues to show the correct Value all the way up to prepareForSegue. Weird!
According to your logs and code , you are entering the switch block twice. Which means you are entering the actionSheet:clickedButtonAtIndex: method twice. So each time you enter the method
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
statement is executed twice, in turn creating two objects. You can see this by doing a fetch from the store.
So you are checking for properties in two different objects and hence the null.
If you are using just one managed object, you can probably add a check for nil for the object before executing insertNewObjectForEntityForName:inManagedObjectContext:. This will make sure you are using the same object.
If you are using more than one object at the same time use the object id or some unique key to identify your object and manipulate it.
Edit:
You can check for nil with the following code:
if(letsMeet==Nil){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}
This will work only, if the object you are calling the actionSheet:clickedButtonAtIndex: method is always in memory. But since you are persisting you might want to fetch the object from the store and then check for no. of objects.
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext]];
NSArray *objectArray = [managedObjectContext executeFetchRequest:request error:&error]
if(objectArray.count==0){
letsMeet = (LetsMeet *) [NSEntityDescription insertNewObjectForEntityForName:#"LetsMeet" inManagedObjectContext:managedObjectContext];
}else{
letsMeet = (LetsMeet *)[objectArray objectAtIndex:0];
}
Note: If you need to persist only a couple of variables, core-data might be an overkill. Use NSUserDefaults instead and keep it simple.

Init NSManagedObject subclass

I would like to know if it's possible to init a subclass of NSManagedObject ?
I have a class "Actualite" which is a subclass of NSManagedObject and when I want to initialize this class, I get this error :
"CoreData: error: Failed to call designated initializer on NSManagedObject class Actualite", and the app crashes after this message "-[Actualite setTitre:]: unrecognized selector sent to instance 0x8433be0"
Here is my code :
-(void) recupererActualites {
listeNouvellesActualites = [[NSMutableArray alloc] init];
// Convert the supplied URL string into a usable URL object
NSURL *url = [NSURL URLWithString:FACE06_RSS];
// Create a new rssParser object based on the TouchXML "CXMLDocument" class, this is the
// object that actually grabs and processes the RSS data
CXMLDocument *rssParser = [[CXMLDocument alloc] initWithContentsOfURL:url encoding:NSUTF8StringEncoding options:0 error:nil];
// Create a new Array object to be used with the looping of the results from the rssParser
NSArray *resultNodes = NULL;
// Set the resultNodes Array to contain an object for every instance of an node in our RSS feed
resultNodes = [rssParser nodesForXPath:#"//item" error:nil];
NSMutableArray* tmp = [[NSMutableArray alloc] init];
for (CXMLElement* resultElement in resultNodes) {
// Create a temporary MutableDictionary to store the items fields in, which will eventually end up in blogEntries
NSMutableDictionary *blogItem = [[NSMutableDictionary alloc] init];
NSMutableArray* categories = [[NSMutableArray alloc] init];
// Create a counter variable as type "int"
int counter;
// Loop through the children of the current node
for(counter = 0; counter < [resultElement childCount]; counter++) {
// Add each field to the blogItem Dictionary with the node name as key and node value as the value
if([[[resultElement childAtIndex:counter] name] isEqual:#"category"])
[categories addObject:[[resultElement childAtIndex:counter] stringValue]];
else {
if ([[resultElement childAtIndex:counter] stringValue] != nil)
[blogItem setObject:[[resultElement childAtIndex:counter] stringValue] forKey:[[resultElement childAtIndex:counter] name]];
else
[blogItem setObject:#"" forKey:[[resultElement childAtIndex:counter] name]];
}
}
Actualite* actu = [[Actualite alloc] init];
[blogItem setObject:categories forKey:#"categories"];
[actu initWithDictionnary:blogItem];
[tmp addObject:actu];
//[actu release];
[categories release];
[blogItem release];
}
listeNouvellesActualites = tmp;
[rssParser release];
resultNodes = nil;
// Stockage des actualités en local
[self stockerActualites];
}
And the initWithDictionary method set all the attributes of the Actualite class.
I also tried
Actualite* actu = [[Actualite alloc] initWithEntity:[NSEntityDescription entityForName:#"Actualite" inManagedObjectContext:managedObjectContext] insertIntoManagedObjectContext:managedObjectContext];
and
Actualite* actu = (Actualite*)[NSEntityDescription entityForName:#"Actualite" inManagedObjectContext:managedObjectContext];
instead of
Actualite* actu = [[Actualite alloc] init];
The errors disappear but the app stops at this point. I don't know what can I do...
Is someone already had this problem ?
Thanks a lot !
The idea is that you ask for a new object to be created inside a context and then you use it:
Actualite* actu = [NSEntityDescription insertNewObjectForEntityForName:#"Actualite" inManagedObjectContext:managedObjectContext];

Saving an object to array using NSMutableDictionary

I have been trying to add an object as an NSMutableDictionary to my array, which I am accessing from another view, and It doesn't seem to work. I want to be able to store the data in a plist which I access from a NSDictionary.
-(void)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
alarmArrayCopy = alarmViewController.alarmsTime;
NSMutableDictionary *newAlarm = [[NSMutableDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[self.navigationController dismissModalViewControllerAnimated:YES];
[newAlarm release];
}
UPDATE: How do I add an NSDictionary to my plist database (my db is an array)?
Here is some new code, I updated the NSMutableDictionary to NSDictionary because in my plist you can only have normal dictionaries not a mutable one. But now it crashed and gives me a Thread 1:Program received signal: "SIGABRT".
NSString *path = [[NSBundle mainBundle] bundlePath];
NSString *finalPath = [path stringByAppendingPathComponent:#"data.plist"];
// Adding object for alarm to AlarmViewController
NSDictionary *newAlarm = [[NSDictionary alloc] init];
[newAlarm setValue:labelTextField.text forKey:LABEL_KEY];
[newAlarm setValue:[NSString stringWithFormat:#"%#", alarmPicker.date] forKey:TIME_KEY];
[newAlarm writeToFile:finalPath atomically:NO];
or
-(IBAction)saveAlarm:(id)sender {
// Adding object for alarm to AlarmViewController
NSString *time = [NSString stringWithFormat:#"%#", alarmPicker.date];
NSString *label = [NSString stringWithFormat:#"%#",labelTextField.text];
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:label, LABEL_KEY,time, TIME_KEY, nil];
self.alarmArrayCopy = alarmViewController.alarmsTime;
[alarmArrayCopy addObject:(newAlarm)];
// Dismissing and tiding up.
[newAlarm release];
[self.navigationController dismissModalViewControllerAnimated:YES];
}
First, you should use setObject:forKey: method for adding objects to NSMutableDictionary. Second, you should use initWithObjectsAndKeys: method if you are using NSDictionary.
The setValue:forKey is a method of the Key Value Coding protocol. That was described at here “
Where's the difference between setObject:forKey: and setValue:forKey: in NSMutableDictionary?
”
So, you should do that,
NSDictionary *newAlarm = [[NSDictionary alloc] initWithObjectsAndKeys:
labelTextField.text, LABEL_KEY,
alarmPicker.date, TIME_KEY, nil];
[newAlarm setValue:alarmPicker.date forKey:TIME_KEY];
I am not quite sure, but I guess your error is because you can't send an instance of NSDate object to setValue:forKey method. You may use either setObject:forKey or change NSDate to NSString by [NSString stringWithFormat:"%#", alarmPicker.date].
Hope that helps.

Printing Core Data

I'm working on a program and I have created a fetch request to grab the data that I need to print. I'm able to log information like this:
2010-10-03 16:57:10.362 lzshow7.2[2537:10b] <NSManagedObject: 0x2ca120> (entity: Song; id: 0x2afcb0 <x-coredata://CF5A85CE-BE0F-4ADC-979A-7F4214A8FB19/Song/p9> ; data: {
cueName = Freedom;
cueNo = 014;
cueNotes = nil;
songToInstrument = "<relationship fault: 0x2b1800 'songToInstrument'>";
})
How do I seperate the properties like cueName, cueNo, cueNotes out to be printed?
Here is the fetch request:
//Managed object context???
NSLog(#"setting Managed object stuff");
NSManagedObjectContext *context=[[[NSDocumentController sharedDocumentController] currentDocument] managedObjectContext];
NSLog(#"Second line of Managed object stuff");
//fetch request:
NSLog(#"Starting to fetch:");
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Song" inManagedObjectContext:context];
[request setEntity:entity];
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"cueNo" ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptors release];
[sortDescriptor release];
NSError *error;
NSMutableArray *mutableFetchResults = [[context executeFetchRequest:request error:&error] mutableCopy];
for (id obj in mutableFetchResults)
NSLog(#"%#", obj);
NSLog(#"finished looping");
//Error handling
if (mutableFetchResults == nil) {
// Handle the error.
}
//[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
}
Any help would be greatly appreciated.
Thank you,
Loren
You use basically the opposite of how you stored the values in your managedObject
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSLog(#"%# %# %#", name, number, notes);
if you've created a custom Class of your entity you could add this method:
- (NSString *)description {
NSString *name = [song valueForKey:#"cueName"];
NSNumber *number = [song valueForKey:#"cueNo"];
NSString *notes = [song valueForKey:#"cueNotes"];
...
NSString *returnString = [NSString stringWithFormat:#"%# %# %#", name, number, notes];
return returnString;
}
With this method you can just use NSLog(#"%#", object); to get a nice formatted output

Resources