我使用的是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
}
答案 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)
}
}
}
}
}