AppDelegate.Swift のapplicationDidEnterBackgroundメソッドとapplicationWillEnterForegroundメソッドがその名の通りアプリが背面に回ったときと前面に来たときに呼ばれます。
ただ前面・背面に来たときの処理を全てここに記述するのは非現実的なのでViewController単位に分けます
Swiftでアプリがホーム画面から復帰したときのイベントを通知する
https://www.crunchtimer.jp/blog/technology/ios/700/
まずAppDelegate.Swiftに以下の修正を加えます
/**
アプリケーションが背面に回ったときに呼ばれる
*/
func applicationDidEnterBackground(application: UIApplication) {
// バックグラウンド時、"applicationDidEnterBackground" を通知
let n = NSNotification( name: "applicationDidEnterBackground", object: self)
NSNotificationCenter.defaultCenter().postNotification(n)
}
/**
アプリケーションが前面に来たときに呼ばれる
*/
func applicationWillEnterForeground(application: UIApplication) {
// フォアグラウンド時、"applicationDidEnterBackground" を通知
let n = NSNotification( name: "applicationWillEnterForeground", object: self)
NSNotificationCenter.defaultCenter().postNotification(n)
}
これでイベント発生時に通知を送ることができるようになります
ViewControllerで通知を受け取る
各ViewControllerで通知を受け取れるようにします。
http://qiita.com/taka000826/items/2460869a01766fdd221a
import UIKit
/**
各種便利機能を追加したUIViewController
継承して使用する
*/
class CustomUIViewController: UIViewController {
/** 画面を表示する直前に呼ばれる */
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
print("applicationDidEnterBackgroundの登録")
print("applicationWillEnterForegroundの登録")
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationDidEnterBackground:", name: "applicationDidEnterBackground", object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "applicationWillEnterForeground:", name: "applicationWillEnterForeground", object: nil)
}
/**
背面に回った時の処理
必要に応じて継承先で実装すること
*/
func applicationDidEnterBackground(notification: NSNotification) { }
/**
前面に復帰した時の処理
必要に応じて継承先で実装すること
*/
func applicationWillEnterForeground(notification: NSNotification) { }
/** 画面が破棄される直前に呼ばれる */
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
print("applicationDidEnterBackgroundの登録解除")
print("applicationWillEnterForegroundの登録解除")
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
NSNotificationCenter.defaultCenter().addObserver はこういう通知が来たときにこいうメソッドが呼ばれますよ〜といったメソッドです
利用方法はUIViewControllerを継承するところをCustomUIViewControllerに変更してapplicationDidEnterBackgroundとapplicationWillEnterForegroundをオーバーライドするだけ
あるいは直接書いてもいい