[英]How to parse nested JSON array in TableView Swift?
我正在使用一個返回 JSON 作為響應的端點。 問題是響應json對我來說是一個巨大的數據。 從那以后,我想顯示所有要在 tableview 中顯示的 Surah(englishName) 名稱。 作為 iOS 開發的新手,我盡了最大的努力。 請看一下我的代碼片段,讓我知道我哪里做錯了。
視圖控制器代碼:
var surahName = [Surah]()
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
//MARK: JSON parse
func parseJSON() {
let url = URL(string: "https://api.alquran.cloud/v1/quran/ar.alafasy")
guard url != nil else{
print("URL Founr Nill")
return
}
URLSession.shared.dataTask(with: url!) { (data, response, error) in
if error == nil && data != nil{
do{
self.surahName = try JSONDecoder().decode([Surah].self, from: data!)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}catch{
print(error)
}
}
}.resume()
}
//MARK: Tableview delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return surahName.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:QuranAudioCell = tableView.dequeueReusableCell(withIdentifier: "cell") as! QuranAudioCell
let arrdata = surahName[indexPath.section].data.surahs
cell.nameLbl.text = arrdata[indexPath.row].englishName
return cell
}
問題是它沒有在 tablview 中打印任何東西。
將第一行更改為
var surahNames = [EnglishName]()
內部 do-catch 塊更改
self.surahName = try JSONDecoder().decode([Surah].self, from: data!)
進入
let response = try JSONDecoder().decode(Surah.self, from: data!)
self.surahName = response.data.surahs
現在在 cellForRowAtIndexPath 里面做這個
let surah = surahName[indexPath.row]
cell.nameLbl.text = surah.englishName
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.