[英]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.