ios - 如何通过 iOS 通知中心发送和接收 JSON?

标签 ios json swift

我正在使用 swiftyJSON,“response”是一个 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
}

最佳答案

发生这种情况是因为 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)
                }
            }
        }
    }
}

关于ios - 如何通过 iOS 通知中心发送和接收 JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35026484/

相关文章:

ios - 使用分页时,iOS TableView 应包含多少行?

ios - 如何根据其中的元素更改 UIView 高度

iOS Pusher 客户端不会自动重新连接

ios - 从另一个类访问 UISegmentedControl @IBOoutlet

ios - 如何访问 View Controller 扩展中的 View

javascript - React Native 中的表单验证

ios - 我想为每个 VC 设置导航颜色为不同颜色

json - 处理来自 POST 请求的 JSON 响应

jquery - JsonP 返回 "Uncaught SyntaxError: Unexpected token :"AngularJS -routingnumbers.info

php - 如何逐行解析 JSON 数组