NSNotificationCenter addObserver in Swift 質問する

NSNotificationCenter addObserver in Swift 質問する

Swift でオブザーバーをデフォルトの通知センターに追加するにはどうすればよいですか? バッテリー レベルが変わったときに通知を送信するこのコード行を移植しようとしています。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];

ベストアンサー1

Swift 4.0 および Xcode 9.0+:

通知を送信(投稿):

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)

または

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"])

通知を受信(取得):

NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)

受信した通知の関数メソッド ハンドラー:

@objc func methodOfReceivedNotification(notification: Notification) {}

Swift 3.0 および Xcode 8.0+:

通知を送信(投稿):

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil)

通知を受信(取得):

NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)

受信した通知のメソッド ハンドラー:

func methodOfReceivedNotification(notification: Notification) {
  // Take Action on Notification
}

通知を削除:

deinit {
  NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil)
}

Swift 2.3 および Xcode 7:

通知を送信(投稿)

NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)

通知を受け取る(取得する)

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil)

受信した通知のメソッドハンドラ

func methodOfReceivedNotification(notification: NSNotification){
  // Take Action on Notification
}


過去の Xcode バージョンの場合...



通知を送信(投稿)

NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil)

通知を受け取る(取得する)

NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil)

通知を削除

NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed

受信した通知のメソッドハンドラ

func methodOfReceivedNotification(notification: NSNotification) {
  // Take Action on Notification
}

クラスまたはターゲットメソッドに@objcアノテーションを付ける

@objc private func methodOfReceivedNotification(notification: NSNotification) {
  // Take Action on Notification
}

// Or

dynamic private func methodOfReceivedNotification(notification: NSNotification) {
  // Take Action on Notification
}

おすすめ記事