Utility of notification 'UIApplicationDidEnterBackgroundNotification' - objective-c

I am using Cordova 2.1.0 for IOS app development. Since, I am new to app development, I have a very basic question.
I am using applicationDidEnterBackground method to handle app control when app enters background. But i want to understand the utility of UIApplicationDidEnterBackgroundNotification which is sent when the app is entering the background. In what way can i use this notification and other notifications(like UIApplicationWillEnterForegroundNotification, etc.) sent by the system. What is the USP of these notifications.

According to the documentation, the method applicationDidEnterBackground: tells the UIApplication's delegate that the application is now in the background. In Cocoa, many delegate messages have corresponding UINotifications that are also sent. This is no exception.
According to the documentation:
The application also posts a UIApplicationDidEnterBackgroundNotification notification around the same time it calls this method to give interested objects a chance to respond to the transition.
Therefore, if there are objects in your object graph that need to respond to the state transition, they can observe this notification. I'm not sure there's really an unstated purpose beyond allowing all objects in the graph to respond to application state transition. I suppose if you had a long-running task to perform somewhere down the object hierarchy when the application transitions to background task you could use beginBackgroundTaskWithExpirationHandler: in a manner similar to what you do in the applicationDidEnterBackground.
EDIT:
// example, save NSArray *_myArray to disk when app enters background
// this is contrived, and untested, just meant to show how you can
// observe the UIApplicationDidEnterBackgroundNotification and save state
// in an arbitrary point in the object graph. (as opposed, or in addition to, the
// application's delegate.
// long-running tasks, e.g. web service connections, etc. will need to
// get a background task identifier from the UIApplication and manage that.
__block id enteredBackground = nil;
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
enteredBackground = [center addObserverForName:UIApplicationDidEnterBackgroundNotification
object:nil
queue:nil
usingBlock:^(NSNotification *note) {
[_myArray writeToFile:#"/path/to/you/file" atomically:YES];
}];

Related

Is There A Lost Focus Window Event in Objective C?

Coming from a .NET background I'm used to events getting fired so trapping a lost focus event is easy but I'm not sure how to do this in Obj-C. Basically I want my app to know when another application has gotten focus and it no longer has it so it can perform some actions.
Can you please tell me how I can implement this kind of functionality in Obj-C for an OSX app?
Have a look at the NSWindow notifications. Specifically, you're interested in NSWindowDidBecomeKeyNotification and NSWindowDidResignKeyNotification. You can also create a delegate for the window and implement its windowDidBecomeKey: and windowDidResignKey: methods, as noted in the NSWindowDelegate protocol documentation.
Or, if you just wanted to know when the application (not a window) has gained focus, you can subscribe to the NSApplicationDidBecomeActiveNotification. Likewise, NSApplicationDidResignActiveNotification will notify you when your app loses focus. These notifications are discussed more here. You can also implement applicationWillBecomeActive: and applicationWillResignActive: in the application delegate.
It's unclear if you want notification of a single window losing focus or notification of your entire app losing focus. My answer here provides notification for the entire application losing focus. (See mipadi's answer if you just want to know when one of your app's window loses focus.)
Observe the appropriate notification:
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:#selector(appDeactivated:)
name:NSWorkspaceDidDeactivateApplicationNotification
object:nil];
Then add the handler method:
-(void) appDeactivated:(NSNotification *)notification
{
NSRunningApplication* app = [notification.userInfo objectForKey:#"NSWorkspaceApplicationKey"];
if (app == [NSRunningApplication currentApplication]) {
// your cleanup code here
}
}

how to receive NSWorkspace and accessibility notifications on another thread

I am trying to do window management, but I need the code running on a separate thread.
The first thing I need to do is subscribe to app notifications like this:
NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter];
NSString *not = NSWorkspaceDidLaunchApplicationNotification;
[nc addObserver:self selector:#selector(appLaunched:) name:not object:nil];
But if I simply call addObserver on another thread, will the notifications be delivered there instead?
Apple has this reference, but it seems overcomplicated:
https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/Notifications/Articles/Threading.html
If the answer to the first question is no, then why couldn't I just forward the message like this?
NSThread *other;
- (void)appLaunched:(NSNotification*)not {
if([NSThread currentThread] != otherThread)
[self performSelector:#selector(appLaunched:) onThread:other withObject:not waitUntilDone:NO];
else
// do respond to notification
}
The second thing I need to do is add an AXObserver to a runloop on the other thread.
If I call CFRunLoopGetCurrent() from another thread, will a run loop automatically be created like calling [NSRunLoop currentRunLoop] or do a I have to create one?
Observers which are registered using -addObserver:selector:name:object: receive the notification on the thread where it's posted, not where they registered. There's also -addObserverForName:object:queue:usingBlock:, which causes the notification to be received on the specified queue, but that doesn't let you make it arrive on a specified background thread. (Only the main queue is tied to a thread.)
You can shunt a notification to another thread in the manner you suggest. However, the original receiving thread has to be idling to receive the notification in the first place. Or, rather, it has to be idling in order to allow NSWorkspace to detect the condition which causes it to post the notification.
All threads create a runloop for themselves as soon as it's requested. It's basically impossible to observe a thread not having a runloop, so you might as well just act as though the runloop is created when the thread is created.
All of that said, your original goal – "I am trying to do window management, but I need the code running on a separate thread" – is problematic. Many GUI manipulations are not legal from background threads. Also, why do you "need" to do it from a background thread? And if your main thread is not free, you're not going to receive the workspace notifications in the first place.

Notify all loaded ViewControllers of a certain event

I have a class that synchronizes data in the background every once in a while. The user can be anywhere in the app's navigation tree and no matter where the user is I need to be able to update the view controllers with whatever new data I just synchronized.
I put the object in charge of the background thread sync as a property of the SharedAppDelegate.
In a way I need to implement something like the Observer pattern and every time I instantiate a view controller set it to listen to some event on the background sync object so that after every sync I can execute a method in the view controllers that are listening.
I'm not sure what the correct way to do this in Objective-C is or if there is even a better or recommended way.
Use a NSNotification with NSNotificationCenter, which fits precisely your purpose :
in your AppDelegate, when the sync ends, call
[[NSNotificationCenter defaultCenter] postNotificationName:#"SyncEnded" object:mySyncObject]
in every view controller you display, call
_myObserver = [[NSNotificationCenter defaultCenter] addObserverForName:#"SyncEnded" object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note){ ...your UI refresh code... }
also do not forget to remove the observer when it's not needed anymore (view controller deallocated / unloaded / not visible, up to you ), or the NSNotificationCenter will end up crashing :
[[NSNotificationCenter defaultCenter] removeObserver:_myObserver];
A few notes :
This example uses the block-based API to perform the UI refresh work on the main operation queue (implying on the main thread), because you must not perform UIKit operations on any other thread than the main thread. This is likely that your background sync will send its notification on an other thread, so switching to the main thread is necessary. If you want to use the selector-based API, be sure to send the notification on the main thread.
You can register as many observers on the notification as you want, so this matches perfectly your pattern (NSNotifications are usually the best way to notify different app components of an app-wide event like sync end).
The object parameter passed when posting the notification allows you to access the sync object in the observer block using note.object if you need it.

Is it OK for a view to know about its controller?

I'd like my controller to subscribe to notifications from view. However, before doing that, I'd like to confirm if it is OK for a view to know the instance of its controller?
Let me offer you a more specific example of what I have in mind.
My controller creates the view and informs it that it is its controller
self.gameView = [[GameView alloc] initWithController:self];
Once done, it subscribes for notifications from this view
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(saySomething:)
name:#"SaySomethingClever" object:nil];
Meanwhile the view does its thing, but when the right time comes, it posts a notification
[[NSNotificationCenter defaultCenter] postNotificationName:
#"SaySomethingClever" object:gvc];
In order for it to do it, the view needs to know the recipient of the notification (gvc).
I'd like to use this opportunity and as you whether the following is ok:
When initWithController is called, the view
-(id) initWithController: (GameViewController* )g {
gvc = g;
return [self initWithFrame:CGRectMake(0, 0, 480, 300)];
}
where initWithFrame:CGRectMake is a private method that handles specific view stuff.
Everything works fine, however, i wonder whether this approach is morally acceptable
It's not strictly a problem if the view has a reference to its controller, but it looks like your real problem is a misunderstanding of the notification posting method.
The object argument isn't the receiver. Indeed, if it were -- if the poster of a notification had to know the object that was going to get the notification -- that would defeat the entire purpose of the notification. You could just call the appropriate method! The point of notifications is that the poster doesn't need to know the other objects which are listening.
The object argument is actually used by the receiver to distinguish which notifications it should care about. Most frequently, the argument is the poster itself:
[[NSNotificationCenter defaultCenter] postNotificationName:IDidSomethingInteresting
object:self];
but it can in fact be any object.
When registering for notifications, you can specify a particular instance whose notifications you're interested in. This is the object argument to addObserver:... The notification center will then only pass on those notifications whose name and object match what was specified.
Even if you pass nil for the object in addObserver:..., you can check the object of a received notification and only act if the poster was one that you are interested in.
For example, there might be several windows in you application, and you may be interested in knowing when one of them is resized, but you don't care what happens to the rest of them. You would pass just that window instance as the object for addObserver:...
To sum up, your view in this case doesn't need that reference to its controller in order to for the controller to receive notifications posted by the view.
See also: "Posting Notifications"
While the concept is OK, it's not needed in your case:
[[NSNotificationCenter defaultCenter] postNotificationName:#"SaySomethingClever"
object:self];
The object referenced by an NSNotification is usually the object which posts a notification. The whole notification idea is that posters don't need to know about observers.
I would focus on controllers calling other controllers (or ideally model methods).
Allow each view to work with it's main resource and allow the controller for that view to make additional calls.

monitor external application with nsarray (noob)

I'm new to Objective-C and programming in general but I'm beginning to grasp the syntax and have a mostly working application however I'm struggling with one part. I'd like to be able to use the application I'm writing to monitor the activity of another application, namely wether it's open or not.
Ideally when a user clicks a button it will launch remote desktop client and then monitor when remote desktop client closes. I want to know when it closes so that I can either bring my application to the forefront or to restart the computer. Mostly my problems revolve around watching for when remote desktop client closes. Here's what I was thinking of trying:
do {
NSArray* apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:#"com.microsoft.rdc"];
} while ([apps count] >= 1);
The problem with the approach you've posted is that that while loop will block the main thread, preventing your application from doing anything else. You could run that on a background thread to prevent that problem, but that's probably not the best approach.
Instead, take a look at the NSWorkspace class's notifications. One of them is NSWorkspaceDidTerminateApplicationNotification. You should be able to do something like this:
// Put this part in your app delegate's applicationDidFinishLaunching: method, or some other appropriate place
NSNotificationCenter *nc = [[NSWorkspace sharedWorkspace] notificationCenter];
[nc addObserver:self selector#selector(anotherAppDidTerminate:) name:NSWorkspaceDidTerminateApplicationNotification object:nil];
- (void)anotherAppDidTerminate:(NSNotification *)notification
{
NSRunningApplication *app = [[notification userInfo] objectForKey:NSWorkspaceApplicationKey];
if ([app.bundleIdentifier isEqualToString:#"com.microsoft.rdc"]) {
// RDC closed, so do whatever it is you want to here
}
}