我尝试在URLSession.dataTask
运行设置 segue 时获取 json 数据。(每个 json 数据作为发送者)
所以首先,我制作了自己的 Class Array productList = [Product]()
。接下来,我调用getJsonData()
并在其中设置URLSession.dataTask
方法。所以我得到了 Parsed json 数据。但是,当我尝试从 保存该 json 数据(将每个数据附加到productList
)时dataTask completionHandler
,它无法正确保存。(结果productList
为[]
)
我想通过 segue 传递解析的 json 数据。我怎样才能做到这一点?
编辑——
class MainVC: UITableViewController {
var productList = [Product]()
override func viewDidLoad() {
super.viewDidLoad()
getJsonData()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return productList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if let cell = tableView.dequeueReusableCell(withIdentifier: "ItemCell", for: indexPath) as? ItemCell {
let product = productList[indexPath.row]
cell.configureCell(product)
return cell
} else {
return UITableViewCell()
}
}
func getJsonData() {
let url = URL(string: "http://demo7367352.mockable.io")
let request = URLRequest(url: url!)
let defaultSession = URLSession(configuration: URLSessionConfiguration.default)
let task = defaultSession.dataTask(with: request, completionHandler: { (data, response, error) in
do {
guard let data = data, error == nil else {
print("network request failed: error = \(error)")
return
}
guard let rawItem = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else {
print("error trying to convert data to JSON")
return
}
if let fineItem = rawItem["goods"] as? [[String:Any]] {
for item in fineItem {
let eachProduct = Product(title: "", price: 0)
let title = item["TITLE"]
let price = item["PRICE"]
let regDate = item["REGDATE"]
let description = item["DESCRIPTION"]
let iconURL = item["ICON_URL"]
let images = item["IMAGES"]
if let title = title as? String {
eachProduct.title = title
}
if let price = price as? String {
eachProduct.price = Int(price)!
}
DispatchQueue.main.async(execute: {
self.productList.append(eachProduct)
self.tableView.reloadData()
})
}
}
} catch {
print("error trying to convert data to JSON")
return
}
})
task.resume()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToProductDetail" {
if let controller = segue.destination as? DetailVC, let indexPath = tableView.indexPathForSelectedRow {
}
}
}
}
现在,我可以解析来自URLSession DataTask
. 我想实现 tableView 的 segue 来显示细节。但是productList
是空的。所以我不能使用prepareForSegue
with productList[indexPath.row]
。
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToProductDetail" {
if let controller = segue.destination as? DetailVC, let indexPath = tableView.indexPathForSelectedRow {
controller.product = productList[indexPath.row] // productList is nil.
}
}
}