[英]How to show alamofire post request json value in table view using Swift
我嘗試將 json 數據轉換為 swift 5 和 alamofire 5.2 版本的表格視圖
class ViewController: UIViewController, UITableViewDataSource {
struct User {
var buzzyuser_id:Int?
var buzzyuser_image:String?
var buzzyuser_username:String?
init(dic:[String: Any]) {
self.buzzyuser_id = dic["buzzyuser_id"] as? Int
self.buzzyuser_image = dic["buzzyuser_image"] as? String
self.buzzyuser_username = dic["buzzyuser_username"] as? String
}
}
@IBOutlet weak var TableView: UITableView!
private var users = [User] ()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
TableView.dataSource = self
apiload()
}
func apiload() {
let parameters: [String: Any] = ["userid": "1","start":"0"]
let url = "https://example.com/sample.php"
AF.request(url, method: .post, parameters: parameters).responseJSON { response in
switch response.result{
case .success:
//success, do anything
if let json = response.value as? [String: Any] {
for item in json {
// construct your model objects here
self.users.append(User(dic:json))
}
DispatchQueue.main.async {
self.TableView.reloadData()
}
}
break
case .failure:
return
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customcell")
let text = users[indexPath.row]
return cell!
}
}
顯示調試值,但列表僅查看空行我找不到錯誤。
你的問題在這里
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->
UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "customcell")
let text = users[indexPath.row]
return cell!
}
您正在將用戶值分配給參數“文本”,然后您沒有將任何值分配給表格視圖單元格。
如果您正在嘗試...例如在表格上顯示用戶“buzzyuser_username”,然后在
let text = user[indexPath.row]
你應該添加
cell?.textLabel?.text = text.buzzyuser_username
還要確保您正在注冊標識符“customcell”...如果您希望從 xib 文件加載單元格,您可以這樣做(請注意,使用 xib 文件您還可以創建 UITableViewCell 的自定義子類並制作一個帶有用戶圖像 ID 和用戶名的 tableview 行(這就是我認為您要存檔的內容)
self.table?.register(UINib.init(nibName: "YOUR_NIB_NAME", bundle: nil), forCellReuseIdentifier: "customcell")
在注冊重用標識符之后,您可以在表格視圖中使用它,並且如果您還添加了自定義 class 到您的標識符,您可以在表格視圖數據源實現中強制使用它
let cell = tableView.dequeueReusableCell(withIdentifier: "customcell") as! YOUR_CUSTOM_SUBCLASS
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.