How to send/save data when user quits OS X application - macos

I'm working on an OS X application after having worked almost exclusively on iOS apps. If the user quits, say by pressing Command-Q, how can I store some data locally and send some data to my server before the app truly goes out of memory?
On iOS I typically launch a background event when I detect the app going into the background. I've tried listening for "ApplicationWillTerminate" but it doesn't seem to afford me the time to send data.
Should I be intercepting the menu action and performing my work before quitting?
I realize this is a pretty basic question, but my Google-Foo has not led me to a straightforward answer.

applicationWillTerminate is indeed the method to clean up things before the app quits.
Alternatively for an asynchronous way implement applicationShouldTerminate, start you task to store and send the data asynchronously and return NSTerminateLater.
When the task is completed call
[NSApp replyToApplicationShouldTerminate:YES];
Here a snippet as example
- (NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender
{
[self startTaskToSendDataWithCompletion:^() {
[NSApp replyToApplicationShouldTerminate:YES];
}];
return NSTerminateLater;
}

Related

GameKit Match - invite friends between iOS5 and iOS6

I'm trying to implement Game Center invites in a 2-person realtime game. Since invites are not supported in the simulator, I'm testing this on one device running iOS5 and a second one running iOS6 (this is done on purpose).
If I'm using the old-fashioned built-in GKMatchmakerViewController UI on either device to initiate the invite, it works fine both ways - when the iOS5 device initiates the invite as well as when the iOS6 device initiates it.
However, in iOS6 I want to use my own UI to select the player to invite, so I'm using GKMatchRequest to programmatically issue the invite, setting the playersToInvite attribute.
The problem is, the other (iOS5) device gets the push notification, launches the application, runs the [GKMatchmaker sharedMatchmaker].inviteHandler, shows the Game Center UI with the invite details, but even when the iOS6 device sends a finishMatchmakingForMatch request - the iOS5 device doesn't proceed any further. No other handler / delegate is called on the iOS5 machine, no GKMatch object is returned, and it continues to show the Game Center UI with both players marked as "Ready" and with a message saying "Waiting for [iOS6 player] to start the game". The only button on this UI is a Cancel button.
Here's the code snippet that sends the invitation on the iOS6 machine:
GKMatchRequest *request = [[[GKMatchRequest alloc] init] autorelease];
request.minPlayers = 2;
request.maxPlayers = 2;
request.playersToInvite = [NSArray arrayWithObject:playerID];
request.inviteMessage = message;
request.inviteeResponseHandler = ^(NSString *playerID, GKInviteeResponse response)
{
if (response == GKInviteeResponseAccepted)
[[GKMatchmaker sharedMatchmaker] finishMatchmakingForMatch:self.match];
};
[[GKMatchmaker sharedMatchmaker] findMatchForRequest:request withCompletionHandler:^(GKMatch *match, NSError *error)
{
... [whatever]
}];
And here's the code snippet for the invite handler on the iOS5 machine:
[GKMatchmaker sharedMatchmaker].inviteHandler = ^(GKInvite *acceptedInvite, NSArray *playersToInvite)
{
if (acceptedInvite)
{
GKMatchmakerViewController *mmvc = [[[GKMatchmakerViewController alloc] initWithInvite:acceptedInvite] autorelease];
mmvc.matchmakerDelegate = self;
[navController presentModalViewController:mmvc animated:YES];
});
else if (playersToInvite)
{
... [whatever]
}
}
The sequence is as follows:
iOS6 sends a findMatchForRequest request with the iOS5 player id.
A push notification is shown on the iOS5 machine.
The application is launched on the iOS5 machine and the inviteHandler is called.
The GKMatchmakerViewController is shown on the iOS5 machine with the invite details, and the iOS6 user has a spinning "Connecting" status.
The inviteeResponseHandler on the iOS6 machine is called and sends a finishMatchmakingForMatch request.
The status of the iOS6 user in the iOS5 Game Center screen changes from spinning "Connecting" to "Ready", and at this point both players are marked as "Ready".
The iOS6 machine gets a match: player: didChangeState: callback, showing the iOS5 player as GKPlayerStateConnected, so as far as the iOS6 machine is concerned the match process is finished and the game can begin.
Nothing whatsoever happens from now on on the iOS5 machine. It is stuck with "Waiting for [iOS6 user] to start the game" until it is cancelled by a timeout. It never receives any GKMatch object at any point, so it cannot start the game.
Since things work fine if I use the standard Game Center UI on the iOS6 machine rather than a programmable invite, it means that the standard UI must do something more to tell the other machine that the game has to start. However, I browsed through all the relevant Game Center objects and couldn't find anything else to send.
I should mention again that the reverse configuration (iOS5 initiating the invite using the standard UI) works fine on both machines.
Help, anyone?
I am having a similar problem. One of the things I did to partially solve is to use programmatic for ios6 users, and viewController for ios5 users. I think you are doing that too but your inviteHandler code only seems to have viewController code. Were you able to fully solve your issue?

What can you do in CoreBluetooth background delegate calls?

I am using Core Bluetooth in my project. I have included Session Backgrounding to avail its background mode functionality. I have observed that the delegate for peripheral disconnection,
- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error;
gets called in the background mode. However any code I write in this method is not executed except for NSLogs. Can somebody explain exactly what kind of code can be executed here?
My aim is to send this disconnection notification to my server.
Ok it seems it was some issue at my end. According the the documentation your app is woken (in the background) for around 10 seconds when it gets a bluetooth related delegate call.
You can use this time to perform any non view updating task and even request for additional time using beginBackgroundTaskWithExpirationHandler.
My code looks like this.
if ([UIApplication sharedApplication].applicationState == UIApplicationStateBackground) {
[self sendEmailInBackground:peripheral]; //Code to send a server request
return;
}
and its working in the background mode. This also works when the phone is in lock state.

UILocalNotification and alertLaunchImage

Hmmm……
A question about UILocalNotification and the notificaton's alertLaunchImage.
My app uses UILocalNotifiaction(s) to get users' attention. As usual, an alert is presented with "Action" and "Close" buttons. When the user taps Action, the image specified by alertLaunchImage is presented. The alertLaunchImage is a screenshot of of one of the views of the app which is shown after the data is initialized when launched normally.
Here are the 3 cases when the notification is delivered:
App is running in foreground - no alert, no launchImage is shown as designed. No problems.
If my app is running in background when the notification is delivered, the launchImage works like a charm. No problems. The launchImage with no app-related data is shown and then the app fills up the data. This part works seamlessly.
However, if the app is not running when the notification is delivered, the sequence is confusing - or I missed something. The app gets launched and shows the alertLaunchImage instead of the Default image. Then is goes thru several other screens (as part of initialization and data processing) before the actual screen (live version of alertLaunchImage) is shown.
This can get very confusing to the user. My question comes in here. How can this be avoided?
R/-
Sam.!
you can try cleaning up the alert view settings in applicationWillTerminate:
According to the UIApplicationDelegate reference applicationWillTerminate::
"This method lets your application know
that it is about to be terminated and
purged from memory entirely. You
should use this method to perform any
final clean-up tasks for your
application, such as freeing shared
resources, saving user data,
invalidating timers, and storing
enough application state to
reconstitute your application’s
interface when it is relaunched"
HTH,
Oded
If your app is launched by a local notification, you will receive that notification in the options passed to -application:didFinishLaunchingWithOptions:. Based on that, you can write code that navigates to the correct screen without animations.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification *localNotification = [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotification != nil) {
// startup by local notification
} else {
// normal startup
}
}

How do I run code when a user agent process terminates?

What I want
I want a helper app user agent (LSUIElement in Info.plist is True) to add itself to the login items on terminate.
The Problem
I can't get any code to run before the helper app process terminates.
My "add to login items" code runs fine.
Background
I've got a helper app user agent process that runs all the time
On first launch, it adds itself to login items
If the app was moved, on next login, the helper app process can't be found and so isn't launched
What I've Tried
I wonder if I should subclass NSApplication and override terminate: or stop: and put my code in there, but that seems overkill. Surely there's a better way?
I've tried all these different things in the NSApp delegate:
-(void)applicationWillTerminate:(NSApplication *)sender {
[self addHelperAppToLoginItems]
}
-(void)applicationDidTerminate:(NSApplication *)sender {
[self addHelperAppToLoginItems]
}
-(NSApplicationTerminateReply)applicationShouldTerminate:(NSApplication *)sender {
[self addHelperAppToLoginItems]
}
-(void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self
selector:#selector(addHelperAppToLoginItems)
name:NSWorkspaceDidTerminateApplicationNotification
object:nil];
}
-(void)addHelperAppToLoginItems {
// This code never gets called!
}
Why do the NSApplication delegate methods not work with a user agent process?
And how can I get the process to check the login items on terminate?
I'd be very grateful for any help. Thanks!
UPDATE 1 6/2/11
After some further digging, the problem is more that processes never really get quit, it's more common for them to get killed by the OS.
This means when you choose to "Quit" a process in Activity Monitor or you shut down the computer, the terminate delegate methods don't get called.
When the following Applescript is run, the delegate methods do get called:
tell application "System Events"
tell application "LapsusHelperApp"
quit
end tell
end tell
After some further digging, the problem is more that processes never really get quit, it's more common for them to get killed by the OS.
This is because you have sudden termination enabled for your application. It's opt-in, so simply remove that key-value pair from your Info.plist and you will then start getting applicationWillTerminate: messages.
Also, the Terminate button in Xcode (at least in 3.x) always works the same way sudden termination does, so you will never get a applicationWillTerminate: message when terminating your app from Xcode.
By the way:
applicationWillTerminate: is a notification message, so its argument is an NSNotification object, not an NSApplication object.
There is no applicationDidTerminate:. A moment's reflection will reveal why. ☺

Opening a url on launch

What method must I implement in my cocoa application’s delegate so that on launch, it’ll open a url? (http/https, in this case) I’ve already implemented the url schemes, I just need to know how I can get my application to open on a url notification.
Update: I’m sorry, I wasn’t very clear. My application IS a browser that support https/http urls, but can only open them when it’s already running. What can I do to implement support for open urls in my app on launch?
When an application finishes launching on OS X, NSApp (the global NSApplication instance for the program) sends its delegate the applicationDidFinishLaunching: message (via the notification system). You can implement that method in your delegate to handle the notification and open a browser window in response, using NSWorkspace. Something like the following would work:
// Your NSApp delegate
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification
{
[[NSWorkspace sharedWorkspace] openURL:[NSURL URLWithString:#"http://www.example.com/"]];
}
It's not a delegate method. You need to implement an Apple Event handler for the getURL event.
As luck would have it, this is exactly the case Apple uses to demonstrate implementing an Apple Event handler.
I already had implemented the getURL event, so that alone isn’t enough to get the application to open a url on launch. The trick is that the AppleEvent must be installed in applicationWillFinishLaunching: not applicationDidFinishLaunching:. Otherwise, the event isn’t sent at all because the app hasn’t registered it in time.
To implement a protocol handler that you can select (in Safari preferences, for example) as the "default browser" and which will launch in response to HTTP / HTTPS, you need to do a few things.
Add .scriptSuite and .scriptTerminology files to your project resources. These will tell Mac OS X that you'll be handling the GetURL command.
Add a CFBundleURLTypes key to your Info.plist file listing the "URL Schemes" that your app will handle.
Also in Info.plist, add the NSAppleScriptEnabled key with the value YES.
Add a new class to your application as a subclass of NSScriptCommand and implement the -(id)performDefaultImplementation selector. From within this function you will find the clicked URL in [self directParameter]. Pass this on to your app's URL handler!
For the full details check out the article:
http://www.xmldatabases.org/WK/blog/1154_Handling_URL_schemes_in_Cocoa.item

Resources