gpt4 book ai didi

ios - 如何使用swift 3将解析后的json数据保存到数组中

转载 作者:行者123 更新时间:2023-11-29 00:12:33 25 4
gpt4 key购买 nike

所以我从服务器收到了一些 json 数据,现在我试图将它保存为一个数组,这样我就可以用它填充一个 TableView ,但是我在做这件事时遇到了麻烦这是我的代码:

class UserInfo : UIViewController{
var main = ""
session.dataTask(with: url) { (data, response, error) in
if let response = response {
print (response)
}
if let data = data {
let json = (try? JSONSerialization.jsonObject(with: data, options: []))
print(json)
guard let array = json as? [Any] else {return}
for info in array {
guard let infoDict = info as? [String : Any] else{return}
//there is a declared var called main
//main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error
self.main = infoDict["Title"] as! String
print (self.main)
}
}
}.resume()
}

最佳答案

首先,您必须在请求范围之外声明 ary。然后你必须将你的数据存储在同一个 ary 中。

var ary: NSMutableArray = NSMutableArray()

session.dataTask(with: url) { (data, response, error) in
if let response = response {
print (response)
}
if let data = data {
let json = (try? JSONSerialization.jsonObject(with: data, options: []))
print(json)
guard let array = json as? [Any] else {return}
for info in array {
guard let infoDict = info as? [String : Any] else{return}
//there is a declared var called main
//main is the one i want save as an array, currently its a variable. i tried to save it as an array by using as! Array but i get error
self.main = infoDict["Title"] as! String
self.ary.add(self.main)
print (self.main)
}
print("Final array is :::",self.ary)
}
}.resume()

尝试上面的代码。希望它对您有用。

关于ios - 如何使用swift 3将解析后的json数据保存到数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46035963/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com