TIMEX
TIMEX

Reputation: 271774

How do I post and receive JSON via iOS notification center?

I'm using swiftyJSON and "response" is a JSON object.

How do I pass it to a notification and then receive it on the other end?

self.center.postNotificationName(NotificationCenters.JSONObjectReceived, object: self, userInfo: response)  //how?

And then in another class:

func JSONObjectReceived(notification: NSNotification!){
    let response = notification.userInfo //response should be JSON type now
}

Upvotes: 3

Views: 1109

Answers (1)

shpasta
shpasta

Reputation: 1933

This happens because JSON is a struct. And to pass in notification you can use json.object value:

import UIKit
import Foundation
import SwiftyJSON

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Register for notification
        NSNotificationCenter.defaultCenter().addObserver(self, selector:"receiveNotification:", name: "my_notification", object: nil)

        // Create JSON object
        let jsonString: String = "{\"name\": \"John\"}"
        if let dataFromString = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false) {
            let json = JSON(data: dataFromString)

            // Check that everything is ok with json object
            NSLog("%@", json.description)

            // Post notification
            let userInfo:[String:AnyObject] = ["my_key":json.object]
            NSNotificationCenter.defaultCenter().postNotificationName("my_notification", object: self, userInfo: userInfo)
        }
    }

    func receiveNotification(notification: NSNotification) {
        NSLog("name: %@", notification.name)

        // get json object
        if let userInfo = notification.userInfo {
            if let json = userInfo["my_key"] {

                // find value in json
                if let name = json["name"] as? String {
                    NSLog("name : %@", name)
                }
            }
        }
    }
}

Upvotes: 1

Related Questions