NSNotificationCenter addObserver in Swift

后端 未结 14 1998
难免孤独
难免孤独 2020-11-22 05:23

How do you add an observer in Swift to the default notification center? I\'m trying to port this line of code that sends a notification when the battery level changes.

14条回答
  •  孤街浪徒
    2020-11-22 06:17

    Swift 5 Notification Observer

    override func viewDidLoad() {
        super.viewDidLoad() 
        NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
    }
    
    @objc func batteryLevelChanged(notification : NSNotification){
        //do here code
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)
    
    }
    

提交回复
热议问题