NSNotificationCenter addObserver in Swift

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

    I'm able to do one of the following to successfully use a selector - without annotating anything with @objc:

    NSNotificationCenter.defaultCenter().addObserver(self,
        selector:"batteryLevelChanged:" as Selector,
        name:"UIDeviceBatteryLevelDidChangeNotification",
        object:nil)    
    

    OR

    let notificationSelector: Selector = "batteryLevelChanged:"
    
    NSNotificationCenter.defaultCenter().addObserver(self,
        selector: notificationSelector,
        name:"UIDeviceBatteryLevelDidChangeNotification",
        object:nil)    
    

    My xcrun version shows Swift 1.2, and this works on Xcode 6.4 and Xcode 7 beta 2 (which I thought would be using Swift 2.0):

    $xcrun swift --version
    
    Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)
    

提交回复
热议问题