423 votes

NSNotificationCenter addObserver en Swift

Comment ajouter un observateur en Swift au centre de notification par défaut? Je essaie de porter cette ligne de code qui envoie une notification lorsque le niveau de la batterie change.

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

0 votes

Que demandez-vous précisément ? Comment fonctionne le sélecteur ?

1 votes

Je n'ai pas réalisé que le type "Selector" est juste une chaîne de caractères en Swift. Aucune mention dans la documentation.

0 votes

8voto

Sahil Points 6129

Transmettre des données en utilisant NSNotificationCenter

Vous pouvez également transmettre des données en utilisant NotificationCenter en swift 3.0 et NSNotificationCenter en swift 2.0.

Version Swift 2.0

Transmettre des informations en utilisant userInfo qui est un dictionnaire optionnel de type [NSObject : AnyObject]?

let imageDataDict:[String: UIImage] = ["image": image]

// Poster une notification
 NSNotificationCenter.defaultCenter().postNotificationName(notificationName, object: nil, userInfo: imageDataDict)

// S'inscrire pour recevoir la notification dans votre classe
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: notificationName, object: nil)

// gérer la notification
func showSpinningWheel(notification: NSNotification) {
  if let image = notification.userInfo?["image"] as? UIImage {
  // faire quelque chose avec votre image   
  }
}

Version Swift 3.0

Le userInfo prend maintenant [AnyHashable:Any]? comme argument, que nous fournissons sous forme de littéral de dictionnaire en Swift

let imageDataDict:[String: UIImage] = ["image": image]

// poster une notification
 NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
// `default` est maintenant une propriété, pas un appel de méthode

// S'inscrire pour recevoir la notification dans votre classe
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// gérer la notification
func showSpinningWheel(_ notification: NSNotification) {

  if let image = notification.userInfo?["image"] as? UIImage {
  // faire quelque chose avec votre image   
  }
}

Source transmettre des données en utilisant NotificationCenter(swift 3.0) et NSNotificationCenter(swift 2.0)

0 votes

Ravi d'apprendre que cela vous a aidé :)

8voto

RDC Points 9222

Dans Swift 5

Disons que si vous voulez recevoir des données de ViewControllerB à ViewControllerA

ViewControllerA (Récepteur)

import UIKit

class ViewControllerA: UIViewController  {

    override func viewDidLoad() {
        super.viewDidLoad()

        //MARK: - - - - - Code pour passer des données à travers un observateur de notification - - - - -
        // ajouter un observateur dans le(s) contrôleur(s) où vous voulez recevoir des données
        NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil)
    }

    //MARK: - - - - - Méthode pour recevoir des données par le biais d'une notification postée - - - - -
    @objc func methodOfReceivedNotification(notification: Notification) {
        print("Valeur de la notification : ", notification.object ?? "")
    }
}

ViewControllerB (Expéditeur)

import UIKit

class ViewControllerB: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //MARK: - - - - - Définir les données à envoyer par la notification postée - - - - -
        let objToBeSent = "Message de test de la notification"
        NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: objToBeSent)
    }

}

5voto

Imran Rasheed Points 147

Observateur de notification Swift 5

override func viewDidLoad() {
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(batteryLevelChanged), name: UIDevice.batteryLevelDidChangeNotification, object: nil)
}

@objc func batteryLevelChanged(notification : NSNotification){
    //faire le code ici
}

override func viewWillDisappear(_ animated: Bool) {
    NotificationCenter.default.removeObserver(self, name: UIDevice.batteryLevelDidChangeNotification, object: nil)

}

3voto

leanne Points 766

Je suis capable de faire l'une des choses suivantes pour utiliser avec succès un sélecteur - sans annoter quoi que ce soit avec @objc :

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

OU

let notificationSelector: Selector = "batteryLevelChanged:"

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

Ma version xcrun montre Swift 1.2, et cela fonctionne sur Xcode 6.4 et Xcode 7 beta 2 (qui utilise Swift 2.0) :

$xcrun swift --version

Apple Swift version 1.2 (swiftlang-602.0.53.1 clang-602.0.53)

0 votes

Vous n'avez pas besoin d'annoter avec @objc si votre classe d'observateur hérite de NSObject.

0 votes

Et vous ne devriez pas avoir besoin de convertir explicitement une String en Selector non plus. :)

0 votes

@alfvata: Ma classe d'observateur n'hérite pas de NSObject. Elle hérite de AnyObject, à la manière de Swift. Le fait de convertir explicitement la chaîne en Selector me permet d'éviter de faire tout autre contournement lié à Objective-C.

2voto

Deepak Thakur Points 850

En swift 2.2 - XCode 7.3, nous utilisons #selector pour NSNotificationCenter

 NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(rotate), name: UIDeviceOrientationDidChangeNotification, object: nil)

Prograide.com

Prograide est une communauté de développeurs qui cherche à élargir la connaissance de la programmation au-delà de l'anglais.
Pour cela nous avons les plus grands doutes résolus en français et vous pouvez aussi poser vos propres questions ou résoudre celles des autres.

Powered by:

X