-1

I m getting a string from NSNotification,but facing issue of optional keyword attached with the given string,wants to remove OPTIONAL keyword from string,here is my code:

func getAlertMsg(notification:NSNotification!){
        if let strAlert = notification?.object.debugDescription{
            print(strAlert)
            Helper .showAsAlert(strMessage: strAlert, VC: self)
        }
    }

Response

{
"status": true,
"message": "User created",
"user_detail":{}
}
priyanshu
  • 155
  • 2
  • 11

2 Answers2

-1

For your current code. It should be:

func getAlertMsg(notification: NSNotification) {
    if let string = notification.object as? String {
        Helper.showAsAlert(strMessage: string, VC: self)
    }
}

Also, your notification post should be:

let strMessage = responseVal.value(forKey: "message") as? String
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegAlertMsg"), 
                                object: strMessage) 

Just pass strMessage. Don't bang (!) it or you app will crash when responseVal.value(forKey: "message") as? String fails.

staticVoidMan
  • 19,275
  • 6
  • 69
  • 98
-3

I have Accessed Object From Notification Like This :

@objc func updateActivityDetailWithUserEvent(notification: NSNotification){ //do stuff

    print("notification obj is ",notification)

    let activityData:[String: ActivityFeed] = notification.object  as! [String: ActivityFeed]
    activityObj = activityData ["activityUpdated"]!
    DispatchQueue.main.async {

    //Update UI From Main Thread
        self.setUpdatedCell()


    }

}

// Way to Post Notification and Passing Dictionary as Parameter :

Call It from Your method from where you like to post Notification with Dictionary parameter:

let activityData:[String: ActivityFeed] = ["activityUpdated": activityFeedObj]

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "activityUpdated"), object: activityData)

Here I am taking Dictionary Object from Notification that i have passed for while generation NSNotification, you can follow similar approach for Getting String Value

  • 2
    Too bad I can only use one downvote for that force-unwrapping – mag_zbc Apr 05 '18 at 08:56
  • i have added sample just to give u idea about how i have access object from notification , you can change it as per your requirements. – A.sharma Apr 05 '18 at 09:16