Objective-C Mac OS X Distributed notifications iTunes - objective-c

i need a little help, i currently have a method; updateTrackInfo in my Mac OS X application which gets the artist name, the track name and duration of the track currently being played in iTunes
However i want the app to listen for the distributed iTunes notification; com.apple.iTunes.playerInfo then call the method updateTrackInfo when ever the notification is distributed by iTunes. Please could someone help me, on what i would need to write in both the header and implementation file.
Thanks, Sami.

You're looking for -[NSDistributedNotificationCenter addObserver:selector:name:object:]:
NSDistributedNotificationCenter *dnc = [NSDistributedNotificationCenter defaultCenter];
[dnc addObserver:self selector:#selector(updateTrackInfo:) name:#"com.apple.iTunes.playerInfo" object:nil];
Elsewhere in the same class...
- (void) updateTrackInfo:(NSNotification *)notification {
NSDictionary *information = [notification userInfo];
NSLog(#"track information: %#", information);
}
It even gives you a whole bunch of track information in the notification. Isn't that nice?

Thanks for your help, you helped me correct my code, I had this written up:
- (id) init {
self = [super init];
if (!self) return nil;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(receiveNotification:)
name:#"com.apple.iTunes.playerInfo"
object:nil];
return self;}
- (void) receiveNotification:(NSNotification *) notification {
if ([#"com.apple.iTunes.playerInfo" isEqualToString:#"com.apple.iTunes.playerInfo"]) {
NSLog (#"Successfully received the test notification!");
}}
But it used NSNotificationCenter instead of NSDistributedNotificationCenter. Which is where I was going wrong.
Thanks, Sami.

Related

OCMock notification observer - verifying the object

I've recently started working with OCMock framework and trying to figure out how to use the notification observer. So in my source code I'm observing some notification:
typedef enum {
OperationStatusCompleted,
// Some other statuses
} SomeOperationStatus;
- (void)addObserverForSomeNotification {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(someOperationStatusDidChange:)
name:#"someOperationStatusDidChange"
object:nil];
- (void)backgroundOperationStatusDidChange:(NSNotification *)notification {
id<SomeOperationProtocol> operation = [notification object];
if (operation.status == OperationStatusCompleted) {
// Do something.
}
}
Now I want to add the expectation for that notification in my test:
- (void)testNotification {
id observerMock = OCMObserverMock();
[[NSNotificationCenter defaultCenter] addMockObserver:observerMock name:#"someOperationStatusChanged" object:nil];
[[observerMock expect] notificationWithName:#"someOperationStatusChanged" object:[OCMArg any]];
// run the test ...
}
That by itself works fine and I'm receiving the notification in the test but what I actually want to check is the status of the object of the notification (meaning that I've received a notification with specific object with specific status). Is it possible?
I finally figured out how to do it:
[[observerMock expect] notificationWithName:#"someOperationStatusChanged" object:[OCMArg checkWithBlock:^BOOL(id<IMBBackgroundOperation> param) {
return param.status == OperationStatusCompleted;
}]];

libPusher not receiving pushes (obj c)

I am trying to implement a OS X (10.10) client for the real time bitcoin exchange rate from bitstamp.com. They offer a great api, unfortunately I can't get the websocket api (https://www.bitstamp.net/websocket/) to work in an OS X Objective C app.
Everyone is pointing me to the libPusher Github project (https://github.com/lukeredpath/libPusher) but I tried literally everything I can think of, I can't get it to receive any pushes on 10.10.
Following the wiki page I downloaded the pre-compiled static library and dragged all files into my projects (I also made sure the "copy" checkbox was checked) and my sample applications compiles. Unfortunately, I never see either the "event through block" or "event through delegate" on the console. However I know that trades happened in the mean time, so that can't be the issue. Any ideas?
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
PTPusher* client = [PTPusher pusherWithKey:#"de504dc5763aeef9ff52" delegate:self encrypted:YES];
[client connect];
PTPusherChannel *channel = [client subscribeToChannelNamed:#"live_trades"];
[channel bindToEventNamed:#"trade" handleWithBlock:^(PTPusherEvent *channelEvent) {
// channelEvent.data is a NSDictionary of the JSON object received
NSLog(#"event through block"); // <-- never called
}];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(didReceiveEventNotification:)
name:PTPusherEventReceivedNotification
object:client];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(didReceiveChannelEventNotification:)
name:PTPusherEventReceivedNotification
object:channel];
}
- (void)didReceiveEventNotification:(NSNotification *)notification // <-- never called
{
NSLog(#"event through delegate");
PTPusherEvent *event = [notification.userInfo objectForKey:PTPusherEventUserInfoKey];
}
After talking to the developer I found the problem:
In my code, the PTPusher instance is a local variable defined in the .m file.
However, it needs to be a strong variable defined in the .h file:
#property (strong) PTPusher* client;
Then in the .m file, you can easily use it (don't forget to synthesize it!):
self.client = [PTPusher pusherWithKey:#"de504dc5763aeef9ff52" delegate:self encrypted:YES];
[self.client connect];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(didReceiveEventNotification:)
name:PTPusherEventReceivedNotification
object:self.client];
PTPusherChannel *channel = [client subscribeToChannelNamed:#"live_trades"];

How to send a string along with NSNotification?

I'm trying to write a plugin for phonegap/cordova that allows audio to resume when interrupted by a phone call. I'm using AVAudioSesionInterruptionNotification and it is working well. However, I need to be able to send a string to my event handler, but I can't figure out how.
I'm setting up an event listener here and calling it from the javascript layer:
- (void) startListeningForAudioSessionEvent:(CDVInvokedUrlCommand*)command{
NSString* myImportantString = [command.arguments objectAtIndex:0];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
}
and I'm handling the event here:
- (void) onAudioSessionEvent:(NSNotification *)notification
{
if([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]){
//do stuff using myImportantString
}
}
can't figure out how to pass myImportantString over to onAudioSessionEvent. I know very little Objective-C (hence my use of cordova), so please respond as if you're talking to a child. Thanks!
By the way, I'm simply trying to add a couple of methods on top of cordova's media plugin found here: https://github.com/apache/cordova-plugin-media/tree/master/src/ios
so the code above is the entirety of my .m file minus this part
#implementation CDVSound (extendedCDVSound)
It's probably easier to use the block-based API for adding an observer:
- (void) startListeningForAudioSessionEvent:(CDVInvokedUrlCommand*)command{
NSString* myImportantString = [command.arguments objectAtIndex:0];
id observer = [[NSNotificationCenter defaultCenter] addObserverForName:AVAudioSessionInterruptionNotification
object:nil
queue:nil
usingBlock:^(NSNotification *notification){
if([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]){
//do stuff using myImportantString; you could even skip the use of that
//temporary variable and directly use [command.arguments objectAtIndex:0],
//assuming that command and command.arguments are immutable so that you
//can rely on them still being the same
}
}];
}
By using the block-based API, you can directly reference any variables that are in scope at the time the observer is added in the code which is invoked when the notification is posted.
When you're done observing, you need to remove observer as an observer of the notification.
Like this:
// near the top of MyController.m (above #implementation)
#interface MyController ()
#property NSString *myImportantString;
#end
// inside the implementation
- (void) startListeningForAudioSessionEvent:(CDVInvokedUrlCommand*)command{
self.myImportantString = [command.arguments objectAtIndex:0];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(onAudioSessionEvent:) name:AVAudioSessionInterruptionNotification object:nil];
}
- (void) onAudioSessionEvent:(NSNotification *)notification
{
if([[notification.userInfo valueForKey:AVAudioSessionInterruptionTypeKey] isEqualToNumber:[NSNumber numberWithInt:AVAudioSessionInterruptionTypeEnded]]){
//do stuff using self.myImportantString
}
}

Giving notification to another class with NSNotificationCenter

So my goal is to deliver a notification to another class with using NSNotificationCenter, I also want to pass object with the notification to the other class, how should I do this?
You must first register a notification name
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(startLocating:) name:#"ForceUpdateLocation" object:nil]; // don't forget the ":"
And then post a notification with a dictionary of parameters
[[NSNotificationCenter defaultCenter] postNotificationName:#"ForceUpdateLocation" object:self userInfo:[NSDictionary dictionaryWithObject:#"1,2,3,4,5" forKey:#"categories_ids"]];
and the method will be
- (void)startLocating:(NSNotification *)notification {
NSDictionary *dict = [notification userInfo];
}
Just call any method for posting notifications as described here, for instance :
to post a notification :
-(void)postNotificationName:(NSString *)notificationName
object:(id)notificationSender
userInfo:(NSDictionary *)userInfo;
where userInfo is a dictionary containing useful objects.
On the other side to register for notifications :
-(void)addObserver:(id)notificationObserver
selector:(SEL)notificationSelector
name:(NSString *)notificationName
object:(id)notificationSender;
You could also check Apple's Notification Programming Topics.

Get notification using NSDistributedNotificationCenter for iTunes on song info change

I know you can use [iTunesDNC addObserver:self selector:#selector(updateInfo:) name:#"com.apple.iTunes.playerInfo" object:nil]; to get a notification every time the player changes song/stops/plays/etc. But what I need is a notification every time information is changed on iTunes (ex. song title changed, lyrics changed, artist, etc)
Any suggestions? Im pretty sure I just need to change com.apple.iTunes.playerInfo to something else that is not playerInfo.
I know it should be posible, because there is an app called SongGenie that will change its info if you edit a song's ID3 tags on iTunes or add lyrics.
Thank you!
Yes, there is a way. Every time song info is changed iTunes posts a "com.apple.iTunes.sourceSaved" notification whose userInfo dictionary is the user's library.
You can check out this and other notifications that iTunes sends by listening to every notificaion posted to the Distributed Notification Center.
[[NSDistributedNotificationCenter defaultCenter] addObserver:self
selector:#selector(allDistributedNotifications:)
name:nil
object:nil];
- (void) allDistributedNotifications:(NSNotification *)note
{
NSString *object = [note object];
NSString *name = [note name];
NSDictionary *userInfo = [note userInfo];
NSLog(#"<%p>%s: object: %# name: %# userInfo: %#", self, __PRETTY_FUNCTION__, object, name, userInfo);
}
or use scripting bridge, https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ScriptingBridgeConcepts/AboutScriptingBridge/AboutScriptingBridge.html#//apple_ref/doc/uid/TP40006104-CH3-SW9