I'm developing an app which has to communicate with an external accessory. The app has several requests to send to the external accessory.
My problem:
I'm using observers in different places (classes), I'm adding the following observers in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(observer1:)
name:EADSessionDataReceivedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(observer2:)
name:EADSessionDataReceivedNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(observer3:)
name:EADSessionDataReceivedNotification object:nil];
The 1st Observer works very well, but I'm getting problems with the other two. They don't respond until the first one has been used. Do I need to add something else?
The flow is as follows:
Send a request to ext-acc and fire a flag to know which observer will take the returned data
ext-acc responds with data
The receiver method pushes a notification into notification center.
The observer with the flag in 1 will take the data (at this point do I need to remove the notification since no one else will need it?).
Looks you have a misunderstanding regarding how NSNotificationCenter works. You are registering your object (self) to observe the notification EADSessionDataReceivedNotification three times, each with it's own selector (observer1, observer2, observer3).
So, what is happening is correct for your code as written. When EADSessionDataReceivedNotification is posted, NSNotificationCenter sends the specified selector to each observer. There is no conditional logic or way to cancel a notification.
Given your description, it sounds like you should only be observing the notification once and checking your flag to determine how to process. Something like:
// observe notificaton
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(dataReceived:) object:nil];
// notification handler
- (void)dataReceived:(NSNotification *)notification {
if (someCondition) {
[self handleDataCondition1];
}
else if (aSecondCondition) {
[self handleDataCondition2];
}
else if (aThirdCondition) {
[self handleDataCondition3];
}
else {
// ????
}
}
Related
I have two class which uses NSNotification to communicate with each other.
Currently, i have an issue with notification being fired twice, i've double/triple/even more checked that observer is not added more then 1 time, notification not being posted twice, did global search on my project for same notification.
My code is like below
Added Notification Observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:notification_deleteMediaFromGallery object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(notificationReceiver:) name:notification_deleteMediaFromGallery object:nil];
Notification Receiver
- (void)notificationReceiver:(NSNotification*)notification {
if ([notification.name isEqualToString:notification_deleteMediaFromGallery]) {
if ([[notification.userInfo objectForKey:#"kind"] integerValue]==GalleryKindPhoto) {
//My statements
}
else if ([[notification.userInfo objectForKey:#"kind"] integerValue]==GalleryKindVideo) {
//My statements
}
}
}
Post Notification
dispatch_async(dispatch_get_main_queue(), ^{
[_browser reloadData];
[[NSNotificationCenter defaultCenter] postNotificationName:notification_deleteMediaFromGallery object:nil userInfo:#{#"index":#(_browser.currentIndex), #"kind":#(self.kind), #"function":[NSString stringWithFormat:#"%s",__PRETTY_FUNCTION__]}];
});
I have also tried this solution by EmptyStack but not get it to work.
I'll be very thankful to you if you could help me solve this issue.
Thanks.
Edit
NOTE
I've added observer in my viewdidload, and cant add/remove observer from viewwillappera/viewwillappear or viewdidappear/viewdiddisappear because the next viewcontroller which will be pushed on current viewcontroller will post notifications
I think you need to write dealloc method in your view controller. And remove All Notification observer in dealloc method,
- (void)dealloc
{
// Deregister observer
[[NSNotificationCenter defaultCenter] removeObserver:self name:notification_deleteMediaFromGallery object:nil];
}
Hi please make sure your method is not calling two time from where you are firing notification.
& please add your notification observer in viewWillDisappear method.
I'd like to check and list out or print the Observer which have been added into the Notification Center.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appplicationIsActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
Below is what I'd check, for example:
if(Observer in Notification Center ){
.....
.....
}else{
.....
.....
}
It seems that there is no API to check if your observer in the NSNotificationCenter.
If you want to remove it, just call removeobserver function
https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsnotificationcenter_Class/Reference/Reference.html
How to use UIApplicationDidBecomeActiveNotification?
Should I declare it in viewDidLoad or viewWillAppear to reload data when coming from background to foreground.
Does UIApplicationDidBecomeActiveNotification gets called only when app comes from background to foreground?
Please help.
Thanks.
Sometimes it is useful to have a listener of UIApplicationDidBecomeActiveNotification when you need to make some action in your view controller on wake up from background (in case you entered to background with this view controller on-screen). In such wake up viewWillAppear will not be triggered!
Example of use:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(someMethod) name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidBecomeActiveNotification object:nil];
}
- (void)someMethod
{
<YOUR CODE AT WAKE UP FROM BACKGROUND>
}
Of course, you can also implement all you need at your app delegate class life cycle.
You get this notification if your app was interrupted by a phone call or push notification. Generally, if your application is getting active on screen after interruption.
You can register any class, that is loaded in memory by the moment application will become active as observer to this notification.
Use following code in viewDidLoad:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification object:nil];
Use someMethod to handle this notification. And don't forget to remove this class as observer in dealloc:
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidBecomeActiveNotification
object:nil];
The OP asked about system notifications fired when the app is backgrounded and then foregrounded again. The Notification designed to handle this situation is the UIApplicationDidEnterBackgroundNotification and UIApplicationWillEnterForegroundNotification. If you want a notification that fires for a wider range of situations, such as when you have a system notification, take a phone call, a SMS comes in, or you slide up the control pane, as well as being backgrounded then you will want the UIApplicationWillResignActiveNotification and UIApplicationDidBecomeActiveNotification. It's important to recognize that these are different, since you might only need to react if your app is backgrounded, and not for other scenarios.
Currently I'm only calling one method when application will enter foreground. How do I call various methods in #selector?
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(displayHappyFace)
name:UIApplicationWillEnterForegroundNotification
object:nil];
Just create a separate function for all your other function.
[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(AllFunction)
name:UIApplicationWillEnterForegroundNotification
object:nil];
All functions.
-(void) AllFunction
{
[self displayHappyFace];
[self otherFunction];
}
Add another observer to UIApplicationWillEnterForegroundNotification if you wish to keep the methods' logic separate:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(displayHappyFace)
name:UIApplicationWillEnterForegroundNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(callOtherMethod)
name:UIApplicationWillEnterForegroundNotification
object:nil];
#selector supports only one method. Remember to remove self as the observer before releasing its memory, to avoid messages being passed to a nil object.
You can only put one selector there.
Best practice is to create a new method called handleNotificationName: for each notification.
Example:
- (void)handleUIApplicationWillEnterForegroundNotification:(NSNotification *)aUIApplicationWillEnterForegroundNotification { }
This makes it really easy to figure out where your app handles each notification and makes code maintenance easy.
Inside the handler method you can call whatever methods you need to. You can have conditional logic also based on state you have or based the userInfo dictionary of the Notification ( if it has one ).
Don't forget to remove your notification observer in you object's dealloc method (at least, if not somewhere else because you might not want to always receive the notification depending on the use case)
Last week I asked this question: Refresh the entire iOS app
#Jim advised me to use the notification center. I was not able to figure out how to work with notifications and I was told to ask another question, I tried for the full week to figure it out on my own, so here goes.
I have a view with multiple subviews. One of the subviews is a search bar (not the tableview one, just a custom text box), the user can search for a new person here and the entire app will be updated screen by screen.
When the user taps on the GO button in the search subview I make the call to the server to get all the data. After which I post this notification:
[self makeServerCalls];
[[NSNotificationCenter defaultCenter] postNotificationName:#"New data" object:Nil];
Now in the init of my parent view controller I have a listener
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(viewDidLoad) name:#"New data" object:nil];
I know this is most probably wrong, so can anyone explain to me how to use notifications properly in my situation? Or if there is a better way of doing what I want.
Thanks for any help you can give me.
When you post a notification, it will cause all register observers to be notified. They get notified by having a message sent to them... the one identified by the selector. As mentioned in the comments, you should not use viewDidLoad. Consider this...
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
}
In some early code (viewDidLoad is a good candidate):
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(newDataNotification:)
name:#"New data"
object:nil];
That's a terrible name, BTW. Oh well. This registration says that your self object will be sent the message newDataNotification: with a NSNotification object whenever a notification is posted with the name "New data" from any object. If you want to limit which object you want to receive the message from, provide a non-nil value.
Now, when you send the notification, you can do so simply, like you did in your code:
[[NSNotificationCenter defaultCenter] postNotificationName:#"New data" object:nil];
and that will make sure (for practical purposes) that [self newDataNotification:notification] is called. Now, you can send data along with the notification as well. So, let's say that the new data is represented by newDataObject. Since you accept notifications from any object, you could:
[[NSNotificationCenter defaultCenter]
postNotificationName:#"New data"
object:newDataObject];
and then in your handler:
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
// The new data is stored in the notification object
NewData *newDataObject = notification.object;
}
Or, you could pass the data in the user info dictionary.
[[NSNotificationCenter defaultCenter]
postNotificationName:#"New data"
object:nil
userInfo:#{
someKey : someData,
anotherKey : moreData,
}];
Then, your handler would look like this...
- (void)newDataNotification:(NSNotification *notification) {
// Do whatever you want to do when new data has arrived.
// The new data is stored in the notification user info
NSDictionary *newData = notification.userInfo;
}
Of course, you could do the same thing with the block API, which I prefer.
Anyway, note that you must remove your observer. If you have a viewDidUnload you should put it in there. In addition, make sure it goes in the dealloc as well:
- (void)dealloc {
// This will remove this object from all notifications
[[NSNotificationCenter defaultCenter] removeObserver:self];
}