NSNotificationCenter addObserver in Swift

后端 未结 14 2403
难免孤独
难免孤独 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:12

    A nice way of doing this is to use the addObserver(forName:object:queue:using:) method rather than the addObserver(_:selector:name:object:) method that is often used from Objective-C code. The advantage of the first variant is that you don't have to use the @objc attribute on your method:

        func batteryLevelChanged(notification: Notification) {
            // do something useful with this information
        }
    
        let observer = NotificationCenter.default.addObserver(
            forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
            object: nil, queue: nil,
            using: batteryLevelChanged)
    

    and you can even just use a closure instead of a method if you want:

        let observer = NotificationCenter.default.addObserver(
            forName: NSNotification.Name.UIDeviceBatteryLevelDidChange,
            object: nil, queue: nil) { _ in print("

提交回复
热议问题