我在swift中处理请求和响应时相当新。这是我坚持使用的代码。我从dataArray中的webservice获取值,但不在tableview中加载。请有人帮忙。
import UIKit
import Foundation
import Alamofire
import SwiftyJSON
class AddOnsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var dataArray = [AnyObject]()
var addOnsURL = "http://econstrademosite.com/food_delivery/?****************"
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.reloadData()
callData()
}
@IBAction func goBackToHome(sender: UIBarButtonItem){
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "base") as! SWRevealViewController
self.present(vc, animated: true, completion: nil)
}
func callData(){
Alamofire.request(addOnsURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject>{
if let innerDict = dict["data"]?["result"]{
self.dataArray = innerDict as! [AnyObject]
print(self.dataArray)
}
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(dataArray.count)
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! exampleTableViewCell
let itemName = dataArray[indexPath.row]["item_name"]
cell.label.text! = itemName as! String
return cell
}
}
答案 0 :(得分:2)
func callData(){
Alamofire.request(addOnsURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject>{
if let innerDict = dict["data"]?["result"]{
self.dataArray = innerDict as! [AnyObject]
print(self.dataArray)
if self.dataArray.count > 0
{
self.tableView.reloadData()
}
}
}
}
}
答案 1 :(得分:1)
不要忘记为delegate
dataSource
和tableView
override func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.delegate = self
self.tableView.dataSource = self
callData()
}
然后在获取数据后重新加载tableView:
func callData(){
Alamofire.request(addOnsURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject>{
if let innerDict = dict["data"]?["result"]{
self.dataArray = innerDict as! [AnyObject]
print(self.dataArray)
self.tableView.reloadData() // you missing this method
}
}
}
}
答案 2 :(得分:0)
您需要更改tableview.reloadData()调用。只要在api调用之后响应并且您将响应存储在dataArray
中,就可以重新加载表。
因此,在您的dataArray
为空时,在viewDidLoad()中重新加载tableview是没有意义的。
所以请更改callData()
这样的方法
func callData(){
Alamofire.request(addOnsURL).responseJSON { response in
let result = response.result
if let dict = result.value as? Dictionary<String, AnyObject>{
if let innerDict = dict["data"]?["result"]{
self.dataArray = innerDict as! [AnyObject]
print(self.dataArray)
}
}
}
}