2016-02-12 74 views
4

我在appDelegate中看到了很少的方法,我不確定是否存儲和重新存儲用戶狀態只是其中的一些涵蓋所有場景?什麼時候應該存儲並重新存儲到ios swift上的keychain?

func applicationWillResignActive(application: UIApplication) { 
    // 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. 

    stopTasks() 
    setSharedPrefrences() 
} 

func applicationDidEnterBackground(application: UIApplication) { 
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. 

    stopTasks() 
    setSharedPrefrences() 
} 

func applicationWillEnterForeground(application: UIApplication) { 
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. 

    startTasks() 
    getSharedPrefrences() 
} 

func applicationDidBecomeActive(application: UIApplication) { 
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. 
    startTasks() 
    getSharedPrefrences() 
    connectGcmService(application) 

} 

func applicationWillTerminate(application: UIApplication) { 
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. 
    stopTasks() 
    setSharedPrefrences() 
    disconnectGcmService(application) 
} 

我應該只在其中一些存儲\恢復? 何時應斷開連接並重新連接到GCM服務?

是我的還原多餘?

保持一個本地標誌說已恢復已不可行,因爲應用程序可能會破壞它?

回答

2

閱讀關於The App Lifecycle: Execution States for Apps的Apple iOS應用程序編程指南。

此外,您在問題中提到的方法的UIApplicationDelegate中的文檔在調用時會包含非常詳細的信息。以the documentation for applicationWillResignActive爲例。

  • didEnterBackground總是被willResignActive之前,所以沒有必要運行相同的代碼。

  • willEnterForeground總是跟着didBecomeActive,但didBecomeActive也可以在其他情況下調用(見下文)。

  • willResignActive可稱爲而不是didEnterBackground被稱爲例如, 10%的電池警告或電話來。如果用戶拒絕接聽電話,您的應用將保持在前臺,並在下一個叫didBecomeActive告訴您該應用再次處於活動狀態。

  • willTerminate從未在現代iOS應用程序中調用過。它在iOS支持多任務之前在iOS 2和3中使用。由於現在應用程序在用戶「退出」時移至後臺,因此不再使用此事件。 (當OS殺死你的應用程序由於內存壓力,而這是在後臺運行,它就會馬上殺了,不執行任何代碼。)

總結:

  • stopTasks/startTasks應在willResignActivedidBecomeActive
  • 保存/恢復用戶數據可以在willResignActive/didBecomeActivedidEnterBackground/willEnterForeground完成。我可能會選擇後者。
+0

請更正您的答案,我會標記它。 「'willresignActive總是在didEnterBackground之前被調用,''vs'」willResignActive可以在不調用didEnterBackground的情況下調用「' –

相關問題