所以我从服务器收到了一些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()
}
答案 0 :(得分:1)
首先,您必须在请求范围之外声明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()
尝试以上代码。希望它对你有用。