首页 > 解决方案 > 无法通过通知发送 json 数据

问题描述

我有NetworkManager类,我在其中请求获取 json 数据并通过 Notification 将它们传递给 TableViewController 但数组为空。有什么问题,或者我应该尝试另一种方法来传递数据,而不是通知?

func loadData() {

guard let url = URL(string: "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest") else {
    
    print("Wrong URL.")
    return
}

let finalURL = url
    var request = URLRequest(url: finalURL)
    request.addValue("my api key", forHTTPHeaderField: "X-CMC_PRO_API_KEY")
    
    let dataTask = URLSession.shared.dataTask(with: request) { (data, responce, error) in
        
        if let jsonData = data {
            
            do {
                
                let cryptoData = try JSONDecoder().decode(Response.self, from: jsonData)
                
                DispatchQueue.main.async {
                    
                    NotificationCenter.default.post(name: .getQuotes, object: cryptoData)
                    
                }                }
            
            catch {
                
                print(error)
            }
        }
    }
    dataTask.resume()
}

表视图控制器

var quotesArray = [CryptoData]()

override func viewDidLoad() {
    super.viewDidLoad()
    
    cryptodata.loadData()

    NotificationCenter.default.addObserver(self, selector: #selector(getQuotesData(notification:)), name: .getQuotes, object: nil)
    
    
}

@objc func getQuotesData(notification: Notification) {
    
    if let receivedQuotes = notification.object as? [CryptoData] {
        
        self.quotesArray = receivedQuotes
        
    }
}

标签: swiftnotifications

解决方案


您可能应该将您的通知对象转换为Response类型而不是[CryptoData]您的getQuotesData(notification:)函数:

@objc func getQuotesData(notification: Notification) {
    if let response = notification.object as? Response {
        self.quotesArray = response.data
    }
}

推荐阅读