swift - 无法通过通知发送 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
}
}
解决方案
您可能应该将您的通知对象转换为Response
类型而不是[CryptoData]
您的getQuotesData(notification:)
函数:
@objc func getQuotesData(notification: Notification) {
if let response = notification.object as? Response {
self.quotesArray = response.data
}
}
推荐阅读
- typescript - 防止 create-react-app TS 编译缩小的库
- swift - 如何在没有用户输入的情况下在 Swift UI 中切换视图?
- c# - 一一引用视图值
- python - 如何获取 matplotlib 颜色图列表?
- python - 如果在 Python 中满足条件,如何从列表中提取值?
- r - 如何包括最后一个系数列
- html - 问:如何加快将设计转换为 html 页面的过程(手动)?
- javascript - firebase.firestore().collection().onSnapshot() 不起作用
- java - Java Unirest 将带有空 JSON 的 POST 请求发送到在 localhost 上运行的服务器,但是在将相同的请求发送到云服务器时工作正常?
- node.js - jsonapi-serializer 覆盖现有的“链接”属性