NSNotificationCenter addObserver in Swift

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

    Swift 3.0 in Xcode 8

    Swift 3.0 has replaced many "stringly-typed" APIs with struct "wrapper types", as is the case with NotificationCenter. Notifications are now identified by a struct Notfication.Name rather than by String. See the Migrating to Swift 3 guide.

    Previous usage:

    // Define identifier
    let notificationIdentifier: String = "NotificationIdentifier"
    
    // Register to receive notification
    NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name: notificationIdentifier, object: nil)
    
    // Post a notification
    NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: nil)
    

    New Swift 3.0 usage:

    // Define identifier
    let notificationName = Notification.Name("NotificationIdentifier")
    
    // Register to receive notification
    NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil)
    
    // Post notification
    NotificationCenter.default.post(name: notificationName, object: nil)
    

    All of the system notification types are now defined as static constants on Notification.Name; i.e. .UIDeviceBatteryLevelDidChange, .UIApplicationDidFinishLaunching, .UITextFieldTextDidChange, etc.

    You can extend Notification.Name with your own custom notifications in order to stay consistent with the system notifications:

    // Definition:
    extension Notification.Name {
        static let yourCustomNotificationName = Notification.Name("yourCustomNotificationName")
    }
    
    // Usage:
    NotificationCenter.default.post(name: .yourCustomNotificationName, object: nil)
    

提交回复
热议问题