104
96

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[Swift]起動時、終了時、アクティブになったときなどにメソッドを呼ぶ方法

Last updated at Posted at 2014-10-06

##NSNotificationCenterを使っていい感じのタイミングでメソッドを呼び出す

ViewController.swift
override func viewDidLoad() {
        super.viewDidLoad()

        let notificationCenter = NSNotificationCenter.defaultCenter()
        //アプリがアクティブになったとき
        notificationCenter.addObserver(
            self,
            selector: "functionName",
            name:UIApplicationDidBecomeActiveNotification,
            object: nil)

}

func functionName() {
//コードを書く
}

上の例はアプリがアクティブになったタイミングで呼ばれる。

notificationCenter.addObserverのnameによってタイミングが変わる。

##使えそうなタイミング

###アプリが終了する直前

        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
            self,
            selector: "functionName:",
            name:UIApplicationWillTerminateNotification,
            object: nil)

###アプリがバックグラウンドになるとき

        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
            self,
            selector: "functionName:",
            name:UIApplicationDidEnterBackgroundNotification,
            object: nil)

###アプリ起動直後

        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
            self,
            selector: "functionName:",
            name:UIApplicationDidFinishLaunchingNotification,
            object: nil)

###デバイスの向きが変わる直前

        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
            self,
            selector: "functionName:",
            name:UIApplicationWillChangeStatusBarOrientationNotification,
            object: nil)

通知の仕組みを使ってメソッドを呼び出している。
いろいろな場面で使えそう。

##好きなタイミングで呼び出す

  notificationCenter.postNotificationName("name", object: self, 
                                                             userInfo: nil)
        let notificationCenter = NSNotificationCenter.defaultCenter()
        notificationCenter.addObserver(
            self,
            selector: "functionName",
            name:"name",
            object: nil)

なんども呼び出されることがあるのでfunctionNameのメソッドが終わったタイミングや画面終了のタイミングで

   notificationCenter.removeObserver(self)

をやって消す。

104
96
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
104
96

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?