我想將一個練習JSON加載到表視圖中,我有一個服務函數從一個源代碼獲取數據作爲JSON,並有一個視圖控制器和一個表,我想要加載信息到。代碼中沒有錯誤,但表格加載空白行,調試部分通過打印命令顯示JSON數據。我是一個初學者,所以我很確定我錯過了一個核心元素,但無法解決它!如何將JSON加載到TableView中?
API服務
class ApiService {
static var swiftyJsonVar:JSON?
class func getExerciseData() {
Alamofire.request("https://wger.de/api/v2/exercise/?format=json").responseJSON { (responseData) -> Void in
if((responseData.result.value) != nil) {
swiftyJsonVar = JSON(responseData.result.value!)
print(swiftyJsonVar ?? nil)
}
}
}
視圖控制器
class ExerciseDatabaseController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var ExerciseSearchField: UISearchBar!
@IBOutlet weak var ExercisesTableView: UITableView!
var arrRes = [[String:AnyObject]]() // Array of dictionary
override func viewDidLoad() {
super.viewDidLoad()
let arrRes = ApiService.getExerciseData()
if let resData = ApiService.swiftyJsonVar?["exercise"].arrayObject {
self.arrRes = resData as! [[String:AnyObject]]
}
if self.arrRes.count > 0 {
self.ExercisesTableView.reloadData()
}
print(arrRes)
// Do any additional setup after loading the view.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return arrRes.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
var dict = arrRes[indexPath.row]
cell.textLabel?.text = dict["name"] as? String
cell.detailTextLabel?.text = dict["description"] as? String
return cell
}
您的網絡電話是異步的。這是你的問題。當你收到數據時,重新加載tableView。在'getExerciseData()'上使用閉包。 – Larme