如何通过iOS通知中心发布和接收JSON?

时间:2016-01-27 00:11:23

标签: ios json swift

我使用的是swiftyJSON和"响应"是一个JSON对象。

如何将其传递给通知,然后在另一端接收?

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

然后在另一个班级:

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

1 个答案:

答案 0 :(得分:1)

这是因为JSON是一个结构。要传递通知,您可以使用json.object值:

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)
                }
            }
        }
    }
}