Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an enum value in a notification in Swift?

I want to send an enum as an object in a notification :

enum RuleError:String {
    case Create, Update, Delete
}

class myClass {

   func foo() {
       NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification", 
                                            object: RuleError.Create)
   }
}

Unfortunately this doesn't work since an enum does not match AnyObject?.

Any idea how to circumvent this problem ?

like image 677
Matthieu Riegler Avatar asked Nov 19 '15 09:11

Matthieu Riegler


1 Answers

The object parameter in the function you're using is the sender, the object posting the notification, not the parameter. Check out the docs here.

You should put the enum value you want to send as a parameter in the user info dictionary and use the following method:

func postNotificationName(_ aName: String,
                   object anObject: AnyObject?,
                 userInfo aUserInfo: [NSObject : AnyObject]?)

In your case:

let userInfo = ["RuleError" : RuleError.Create.rawValue]

NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
        object: self,
        userInfo:userInfo)

And to handle the notification, first register for it:

NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "handleRuleFailNotification:",
        name: "RuleFailNotification",
        object: nil)

Then handle it:

func handleRuleFailNotification(notification: NSNotification) {

        let userInfo = notification.userInfo

        RuleError(rawValue: userInfo!["RuleError"] as! String)
    }
like image 106
Rafa de King Avatar answered Oct 17 '22 22:10

Rafa de King