我正在发出 JSON 请求并从 api 获得一些响应, 我正在解析它,但是优先级对我来说是个问题。
首先我用 alamofire 发送 .post,
其次我得到一些响应并用 swiftyjson 解析它
第三次尝试在 ListView 上使用已解析的数据,但 ListView 在解析之前先工作并返回空 ListView
我尝试将函数放在 viewdidload 的第一行, 我尝试在 viewdidload 中编写 Alamofire 和 swiftyjson 部分。
但它们都不起作用,每次 listviews numberofrowinsection 函数首先起作用。
我不能使用我的帮助程序类或任何静态变量,因为我持有信用卡数据,我不想为此造成一些安全问题。
import UIKit
import CreditCardForm
import Alamofire
import SwiftyJSON
class CreditCardScreen: UIViewController, UITableViewDelegate , UITableViewDataSource {
var json: JSON = []
var data: JSON = []
var token: Parameters = [
"token": Helper.token,
"page_index": "0",
"page_size": "20"
]
@IBOutlet weak var creditCardTableView: UITableView!
@IBOutlet weak var creditCardView: CreditCardFormView!
override func viewDidLoad() {
super.viewDidLoad()
getCreditCardsFromApi()
creditCardView.isHidden = true
creditCardTableView.delegate = self
creditCardTableView.dataSource = self
creditCardTableView.separatorStyle = .none
//creditCardView.changer(value:"10/20")
// Do any additional setup after loading the view.
}
@IBAction func unCreditCardScreen(_ sender: UIStoryboardSegue) {
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.data.count // everytime this line works before than api parsing
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = Bundle.main.loadNibNamed("CreditCardIndexPage", owner: self, options: nil)?.first as! CreditCardIndexPage
let selectedCard = data[indexPath.row]
cell.cardHolderName = selectedCard["card_name"].stringValue
//cell.cardHolderName = isimler[indexPath.row]
cell.cardNumber = "4242424242424240"
cell.backgroundColor = UIColor.clear
cell.write()
return cell
}
func getCreditCardsFromApi(){
Alamofire.request("\(Helper.mainApi)/api/getPaymentCards", method: .post, parameters: token, encoding: JSONEncoding.default).responseJSON{response in
switch response.result{
case .success(let value):
self.json = JSON(value)
self.data = self.json["data"]
case .failure(let error):
print(error.localizedDescription)
}
}
}
}
没有错误消息,但我试图通过断点查看哪个先工作,tableview 函数总是在声明变量后工作。
最佳答案
HTTP 请求需要时间。在加载 TableView 之前,它们不可能完成。正确的做法是在获得数据后重新加载 TableView :
func getCreditCardsFromApi(){
Alamofire.request("\(Helper.mainApi)/api/getPaymentCards", method: .post, parameters: token, encoding: JSONEncoding.default).responseJSON{response in
switch response.result{
case .success(let value):
self.json = JSON(value)
self.data = self.json["data"]
self.tableView.reloadData() <--- this line!
case .failure(let error):
print(error.localizedDescription)
}
}
numberOfCellsInSection
仍将首先被调用,但它会在您收到响应后第二次被调用。
关于swift - 无法在 ListView 中使用已解析的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57351428/