2013-03-06 37 views
1

當用戶在iPhone上殺死應用程序時,有沒有辦法執行最後一項操作?如何在用戶退出iPhone應用程序時執行最後一個操作?

在UIApplicationDelegate中有applicationWillTerminate:但據我所知它不能保證在應用程序終止時被調用。有另一種方法嗎?

+2

它會被調用,但用戶退出不一定是終止。 willResignActive會告訴你關於退出(終止與否)。 – danh 2013-03-06 23:46:57

回答

0

當您使用其中一個項目模板時,與您的應用程序狀態有關的所有方法都在您的AppDelegate中。

將代碼放在applicationWillResignActive:方法中。如果您的應用進入非活動狀態(終止或不活動),它會被調用。

- (void)applicationWillResignActive:(UIApplication *)application 
{ 
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. 
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. 
} 
-1

可以在AppDelegate中使用applicationWillResignActive方法,或者你可以做到以下幾點,如果你要保存的東西,但出於某種原因,你不想做它在應用程序的委託:

- (void) viewDidLoad/init { 
    [[NSNotificationCenter defaultCenter] 
     addObserver:self 
     selector:@selector(myApplicationWillResign) 
     name:UIApplicationWillResignActiveNotification 
     object:NULL]; 
} 

- (void) myApplicationWillResign { 
    NSLog(@"About to die, perform last actions"); 
} 
3

你不能依靠被調用的applicationWillTerminate。從文檔:

對於不支持後臺執行或與iOS 3.x或更低版本鏈接的應用程序,此方法始終在用戶退出應用程序時調用。對於支持後臺執行的應用程序,當用戶退出應用程序時,通常不會調用此方法,因爲在此情況下應用程序只是移至後臺。但是,在應用程序在後臺運行(未掛起)並且系統因某種原因需要終止該應用程序的情況下,可能會調用此方法。

保存任何狀態的適當位置是當應用程序進入後臺時。一旦發生這種情況,就無法知道該應用程序是否會返回到前臺,或者如果它被殺死,然後從頭開始。

+0

'-applicationWillTerminate:'也會在iPhone 3G上被調用(支持它很棘手,但並非不可能),並且文檔還會說「這種方法可能會在應用程序在後臺運行(未掛起)系統因某種原因需要終止它「。爲避免在添加後臺任務/等時被咬傷,最好同時支持這兩個任務。 – 2013-03-07 00:47:26

+0

@rmaddy即使在今天,這個答案是否成立呢?面對一些類似的問題http://stackoverflow.com/questions/42367803/local-banner-notification-for-terminating-app我只想在應用程序終止時顯示通知。任何解決方法? – 2017-02-21 13:38:11

+0

@ sweta.me我的回答有點過時了。事情變了。我已經更新了答案。 – rmaddy 2017-02-21 15:12:40

0

保存狀態的「正確」位置在均爲-applicationDidEnterBackground:-applicationWillTerminate:。不要擔心雙重儲蓄;通常只有其中一個被調用(IME,-applicationWillTerminate:在您的應用程序在後臺死亡時不會被調用)。

買者-applicationDidEnterBackground:保證被調用,因爲它被稱爲你的應用程序進入背景(並因此變得適合,恕不另行通知殺!)。如果您的應用程序背光時該設備的內存不足,可能會導致死機。避免這種情況的最好方法是首先不要使用太多內存。

可以使用 -applicationWillResignActive:,但我不建議這樣做:應用程序成爲非活動相當頻繁。顯而易見的是系統對話框(位置/隱私提示,Wi-Fi,顯示爲警報和警報的通知),TWTweetSheet,以及我懷疑MFMailComposeViewController,MFMessageComposeViewController,通知中心,應用程序切換條(例如更改音軌/啓用方向鎖)。

相關問題