quit the application by setting NSTimer? - objective-c

is their any better way to quit the application programmatically?
recently i made a radio application that have a user setup to set a time using NSTimer for quit the app process ( i mean sleep time). when the time reaches the app should be stop its process and quit.
i used these statements to quit the app when time reaches,
[[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess];
theTimer=[NSTimer scheduledTimerWithTimeInterval:(1.0/1.0) target:self selector:#selector(countTime) userInfo:nil repeats:YES];
counter-=1;
timeLeft.text=[NSString stringWithFormat:#" %d",counter];
if (counter==0.0) {
[theTimer invalidate];
[[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess];
is their any problem by using [[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess]; methods
any other better way to quit the app, or at least freeze the app process..
i need help?

Apple will not approve any application that deliberately suspends or terminates itself. You may use only those methods listed in the official documentation, which does not include suspend or terminateWithSuccess.

I've always used exit(0). I suppose that if you have to run code before the app quitting you should call it before exit(0).
Apple discourages the use of exit() because from the user point of view it looks like a crash. But they also say there is no API call to gracefully terminate your app.
If you're looking for a way to terminate your app without the user pressing home, during sleep time, I assume he won't confuse it with a crash, since he won't be paying attention to your app and exit() leaves no crash log.
So, your options are:
Forget this and just beep after some time to remind him to close the app. (terrible!)
Close the app using your private calls and risk Apple's rejection.
Close the app using exit() and stick with POSIX (accepted) calls.

tanq for your replays, so i just forget about quitting my application programatically. next way is to stop playing my MPMoviePlayerController object. got the next level problem
my settings page for sleepTime and music playing pages, both are different viewControllers
so i can't access MPMoviePlayerController object directly in time settings page, so i created a method on music playing page
MPMoviePlayerController *player=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:#"http://www.radioparadise.com/musiclinks/rp_64aac.m3u"]];
[player prepareToPlay];
[player play];
- (IBAction)StopPlay:(id)sender
{
[player stop];
}
so i created an object for music playing page and i called this method from settings page.,
this is my code in settingsPage
#class MusicPlayingPage;
#interface secondView : UIViewController
{
MusicPlayingPage *audio;
}
and called the method in settingsPage
[audio stopPlay];
control reaches correctly to streamingPage, but it seems like player is not stoping play, i can't access any of these player options [player stop]; , [player pause];
any problem for this method in musicPlayingPage
- (IBAction)StopPlay:(id)sender
{
[player stop];
}
sorry if my question is not understandable.

Related

After implementing facebook login replaceScene freezes

I have implemented facebook login according to https://developers.facebook.com/docs/facebook-login/ios/v2.1#login-apicalls
I have implemented this functionality in my AppDelegate. instead of - (IBAction)buttonTouched:(id)sender method I have same code under -(void)toggleFacebookOnOff; and accessing it from other classes via [(AppDelegate *)[[UIApplication sharedApplication] delegate] toggleFacebookOnOff];
When facebook session is NOT open and I call login method i.e my app redirects to facebook app and then back,calling method [[CCDirector sharedDirector] replaceScene:<#(CCScene *)#> withTransition:<#(CCTransition *)#>] Freezes whole application, no exceptions, no nothing.
Notes:
[[CCDirector sharedDirector] replaceScene:(CCScene *)]; is still functional.
I have noticed that actions are not performed anymore, e.g in different scene I have CCActionEaseInOut to scale sprite from 0.1f to 1.f and this sprite stays scaled.
problems are occurring after app redirects to FB app end then beck, no problem is occurring when I call FBSession openActiveSessionWithReadPermissions with parameter: allowLoginUI:NO.
Anyone has fix for this issue?

UIImagePickerController and application background modes

I’m building an application which supports both video playback and recording (not simultaneously, it’s just two separate features it provides). In order to make the videos play after the app enters background and gets back, I had to add an App plays audio item to Required background modes in the plist (I’m using MPMoviePlayerController for playback).
This, however, causes a problem with my video recording (I’m using UIImagePickerController for it). Basically, even after the picker is dismissed (either by the Cancel button or when it’s finished picking media), the app still keeps the audio recording session running.
If I remove the App plays audio item from the plist, the ImagePickerController’s audio session stops misbehaving, but then I can’t resume the playback of MPMoviePlayerViewController on switching to app from background mode.
Is there a way I can customise the handling of the audio session so that both the MPMoviePlayerController and UIImagePickerController can work properly?
yes, there is a way you can customize the handling of the audio session for what you desire: don't try to set the App plays audio setting.
instead, in your AppDelegate code (which is usually in AppDelegate.m from the simple wizard projects provided), supply code in the applicationWillResignActive: method that will stop the playback in your MPMoviePlayerController, and then use applicationDidBecomeActive: to resume the playback at the point at which you paused it if so desired.
this will not only allow the video to be resumed after a temporary pause, but it will allow you to save the state so that the video can be resumed in case the app is removed from memory or in case the user causes it to be quit.
You can scratch the background modes and instead use notifications to pause/resume your player. See UIApplicationDidBecomeActiveNotification and UIApplicationWillResignActiveNotification in the UIApplication class reference.
You can snag some code and see this implemented in this class. Here is some of the relevant code from that class:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_didBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_willResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
- (void) _didBecomeActive:(NSNotification*)notification {
if (_wasPlaying) {
[_movieController play];
}
}
- (void) _willResignActive:(NSNotification*)notification {
_wasPlaying = _movieController.currentPlaybackRate != 0.0;
if (_wasPlaying) {
[_movieController pause];
}
}

iOS 6 local notifications fail when the phone is locked with app open

I have an app with basic alarm functionality. In my applicationWillResignActive: method I have it setup to create notifications to set off the alarm. This works pretty great, and I believe this is the proper way to do it (let me know if you think there is a better way).
Only in the specific situation, ONLY ON iOS 6, when the application is not "quit" (the home button is never pressed) but the user merely locks the phone or the phone auto locks, the notifications don't go off.
I have traced through the code, and the notifications are indeed being created and it worked perfectly in iOS 5.
Here is my code:
- (void)applicationWillResignActive:(UIApplication *)application
{
[UIApplication sharedApplication].idleTimerDisabled = NO;
[alarm setupForBackground];
if ([alarm isRunning]) {
[alarm stop];
}
}
Here is the notification creation method:
- (void)setupForBackground
{
UILocalNotification* alarmNotification = [[UILocalNotification alloc] init];
if (alarmNotification) {
alarmNotification.fireDate = alarmDate;
alarmNotification.timeZone = [NSTimeZone defaultTimeZone];
alarmNotification.repeatInterval = 0;
alarmNotification.soundName = #"NotificationSound.aif";
[[UIApplication sharedApplication] scheduleLocalNotification:alarmNotification];
}
}
I have been searching for an answer for a while, and I could not find anything stating something about notification changes. Thanks for any help.
I have a semi-solution. Apparently if you add an AlertBody to the notification, then it works.
My belief is that this is a bug in iOS 6. As I mentioned it worked in iOS 5, the documentation makes no mention of having such a requirement, and the notification does work without the AlertBody if the application is quit (the home button is pressed).
Still curious to see if my understanding is correct and if I should file a bug report with Apple.
Thoughts anybody?

How to handle mountain lion notifications clicks

I just wanted to add some notifications to Gyazo app.
I finally able to send notifications to the notifications center http://korniltsev.ru/p/jz6m3Nm.png
however when i click on it and the app is not launched it launches in some strange way:
it shows empty window(even if i set it visibleAtLaunch to 0) and nothing happens;http://korniltsev.ru/p/jz6mvk0.png
the code i'm trying to use is here:
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
NSUserNotification * clicked = [[aNotification userInfo]
objectForKey:NSApplicationLaunchUserNotificationKey];
if (clicked){
[NSApp terminate:self];
return;
}
...
I send notifications like this
NSUserNotificationCenter *manager = [NSUserNotificationCenter defaultUserNotificationCenter];
NSUserNotification *urlNotification = [[NSUserNotification alloc]init];
[urlNotification setTitle:appName];
[urlNotification setInformativeText:url];
[manager deliverNotification:urlNotification];
What am i doing wrong?
[NSApp terminate:self] has a lot of side effects. Are you sure these side effects are not creating your blank window? Have you tried calling [NSApp terminate:self] immediately in applicationDidFinishLaunching and making sure you application quits cleanly in every case? If it does not you will likely have to look at what you are doing in your application's document controller (if you have one) and applicationShouldTerminate.

App modal NSPanel / sheet / dialog + NSThread == window hangs?

I'm in the midst of debugging an extremely unusual problem, and I was wondering if anybody might have any insight into what might be going wrong:
In a controller class from a NIB, I take an NSPanel from that same NIB, and then show it app modally on a NSWindow (that was created by hand in code):
[[NSApplication sharedApplication] beginSheet: myPanel
modalForWindow: window
modalDelegate: self
didEndSelector: #selector(sheetDidEnd:returnCode:contextInfo:)
contextInfo: nil];
[[NSApplication sharedApplication] runModalForWindow: myPanel];
Now, when the "finish" button on that sheet is clicked, I run some code to disable some buttons and fire off a thread to make sure the user input is valid (I have to validate with a remote service). This thread is fired from a separate validator object I create:
// controller calls:
[validator validateCreds: creds
notify: #selector(validationComplete:)
onObject: self];
// validator object
validateInfo: (NSDictionary *)parms
notify: (SEL)notifySelector
onObject: (id)notifyObject
{
// build up data with parms and notify info
[[NSThread detachNewThreadSelector: #selector(remotevalidate:)
toTarget: self withObject: data];
}
Next, when the validation is finished, the validator notifies my controller object:
[notifyObject performSelectorOnMainThread: notifySelector
withObject: results waitUntilDone: NO];
And then my controller object, in the method that the validator object calls, kills the dialog:
- (void)validationComplete: (id)data
{
[[NSApplication sharedApplication] stopModal];
[createTwitterPanel orderOut: nil];
[[NSApplication sharedApplication] endSheet: createTwitterPanel
returnCode: NSOKButton];
}
- (void)sheetDidEnd:(NSWindow *)sheet
returnCode:(int)returnCode
contextInfo:(void *)contextInfo
{
m_returnCode = returnCode;
}
My problem: Although the panel is closed / disappears, the top NSApp runModalForWindow: does not exit until some system event is sent to the window that was showing the dialog. Trying to move, resize, or do anything to the window, or otherwise switching away from the application suddenly causes the method to exit and execution to continue. No amount of waiting seems to help, otherwise, however.
I have verified that all methods being invoked on the controller class are all being invoked on the main app thread.
An even more interesting clue is that the dialog has two controls, a WebView, and an NSTextField: Even if I force the exit of runModalForWindow: by clicking on the window, TABbing between the two controls remains screwed up — it simply never works again. It's like my event loop is horked.
I've tried changing validationComplete: to instead post a notification to the main thread, and I've also played with the waitUntilDone on the performSelectorOnMainThread method, all to no effect.
Any ideas? Things I should try looking at?
From the NSApplication documentation:
abortModal must be used instead of
stopModal or stopModalWithCode: when
you need to stop a modal event loop
from anywhere other than a callout
from that event loop. In other words,
if you want to stop the loop in
response to a user’s actions within
the modal window, use stopModal;
otherwise, use abortModal. For
example, use abortModal when running
in a different thread from the
Application Kit’s main thread or when
responding to an NSTimer that you have
added to the NSModalPanelRunLoopMode
mode of the default NSRunLoop.
So, I learned something today.