javaSEがiOSアプリデザイン、開発に挑む日記

本業java SEがswift、デザインの勉強したことを残しておくブログ

swift フォアグラウンド状態になった時に処理を実施

バックグラウンドにしたアプリを再度フォアグラウンドにした時に更新させるのを検討した時、意外に面倒くさかったのでメモ。

 

AppDelegate.swiftのapplicationWillEnterForeground()でviewControllerに通知を送るようにする

 

func applicationWillEnterForeground(application: UIApplication) {
    var n:NSNotification = NSNotification(name: "【通知の名前】", object: self)
    NSNotificationCenter.defaultCenter().postNotification(n)
}

 

ViewControllerのviewDidLoad()で通知を受け取る通知、受け取った際のセレクタを定義

 

var nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "【セレクタメソッド名】:", name: "【通知の名前】", object: nil)

 

通知受け取り後に実行するセレクタメソッドを実装

 

func selectorMethodName(notification:NSNotification){
    // 処理を記述
}

 

バックグラウンド状態の時の処理の方が難しそう。