mzgkworks

iOSを中心にプログラミング関係について書く

【Swift】ViewControllerでアプリがバックグラウンド/フォアグラウンドになったことを検知する方法

アプリがバックグラウンド/フォアグラウンドになった際に、UIViewControllerで何か処理したい時のやり方。
何もしないとUIViewControllerでは検知できない。

環境

AppDelegate(通知を投げる)

AppDelegateで検知したタイミングで、NSNotificationCenterを使って通知を投げる。

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    func applicationDidEnterBackground(application: UIApplication) {
        // アプリがバックグラウンドへ移行するタイミングを通知
        NSNotificationCenter.defaultCenter().postNotificationName("applicationDidEnterBackground", object: nil)
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // アプリがフォアグラウンドへ移行するタイミングを通知
        NSNotificationCenter.defaultCenter().postNotificationName("applicationWillEnterForeground", object: nil)
    }

ViewController(通知を受信)

ViewController側では、NSNotificationCenterを使って受信する通知を登録しておく。

  • selector: ViewController内で呼ぶメソッド名(任意の名前)
  • name: AppDelegateで設定した通知の名前

selectorのメソッド名の後ろに「:(コロン)」を忘れないこと

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 登録
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "viewWillEnterForeground:", name: "applicationWillEnterForeground", object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "viewDidEnterBackground:", name: "applicationDidEnterBackground", object: nil)
    }

ViewController(受信した通知を処理)

selectorで設定したメソッドを用意して、行いたい処理を記述する。

    // AppDelegate -> applicationWillEnterForegroundの通知
    func viewWillEnterForeground(notification: NSNotification?) {
        println("フォアグラウンド")
    }

    // AppDelegate -> applicationDidEnterBackgroundの通知
    func viewDidEnterBackground(notification: NSNotification?) {
        println("バックグラウンド")
    }