【Swift3】アプリの非アクティブ化時に呼び出す。

アプリを起動した時にロード。アプリがバックグラウンドに入った時にセーブするのに調べた。

参考サイト。
アプリが非アクティブになったことをViewControllerで検知する方法 [UIApplicationDelegate] – MILLEN BOX

UIApplicationDelegateを設定してから、

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(呼び出す関数), name: UIApplicationWillResignActiveNotification, object: nil)

を設置する。
んだったようだが、これもSwift3で変わったらしい。

参考サイト
swift 3.0 のメモ – Qiita

UIApplicationDelegateを設定してから、

NotificationCenter.default.addObserver(self, selector: #selector(呼び出す関数), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
をviewDidLoadにでも書いておくと良いみたい。

import UIKit

class ViewController: UIViewController , UIApplicationDelegate{

(中略)

    override func viewDidLoad() {
        super.viewDidLoad()
        
        loadData()
        

        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.saveData), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
        
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

(中略)

// MARK: セーブ・ロード
    
    func saveData()  {
        // 「ud」というインスタンスをつくる。
        let ud = UserDefaults.standard
        ud.set(count, forKey: "firstCount")
        ud.set(secondCount, forKey: "secondCount")
        ud.set(thirdCount, forKey: "thirdCount")
        ud.set(fourthCount, forKey: "fourthCount")
        ud.set(fifthCount, forKey: "fifthCount")
        
        print("セーブしました。")
    }
    
    func loadData()  {
        let ud = UserDefaults.standard
        count = ud.integer(forKey: "firstCount")
        secondCount = ud.integer(forKey: "secondCount")
        thirdCount = ud.integer(forKey: "thirdCount")
        fourthCount = ud.integer(forKey: "fourthCount")
        fifthCount = ud.integer(forKey: "fifthCount")
        
        print("ロードしました。")
    }
}

こんな感じで。

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です