【问题标题】:How to show data in tableview using Alamofire and swift3?如何使用 Alamofire 和 swift3 在​​ tableview 中显示数据?
【发布时间】:2017-05-17 05:20:42
【问题描述】:

我得到了以下值的响应数组:

["Mallard Point Trailer Court","Golddust","Hagler","McCosh Mill","Graystone","Old Jonesboro","Carlees Mobile Home Court","Denson","Blake","Inverness Cliffs"]

如何使用 alamofire 在我的 tableview 中加载这些数据?

这是我的代码

 let url = Constants.CityUrl + fullName
            print(url)
            Alamofire.request(url, method: .get).responseJSON { response in

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")

                    let response = JSON as! NSArray
}

【问题讨论】:

标签: ios swift swift3 alamofire


【解决方案1】:

为了访问整个类中的数组,你需要像下面这样声明它是全局的,也更喜欢 swift "Array" 而不是 "NSArray",因为它有很多优点

var reponseArray = [String]

也可以从viewDidLoad调用下面的方法

func fetchInformation() {
let url = Constants.CityUrl + fullName
            print(url)
            Alamofire.request(url, method: .get).responseJSON { response in

                if let JSON = response.result.value {
                    print("JSON: \(JSON)")

                    reponseArray = JSON as! Array

         DispatchQueue.main.async {  
             tableView.reloadData()
            //reload on main thread
           }
     }
}

在表视图中数据源方法使用来自reponseArray的信息

【讨论】:

    【解决方案2】:

    在完成块之外添加一个变量并将响应分配给它。 例如:

    let arrResponse: [String]?
    

    在 tableView 委托方法中

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return arrResponse.count
        }
    
    
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
                 var cell:UITableViewCell = self.tableView.dequeueReusableCellWithIdentifier("cell") as UITableViewCell
    
            cell.textLabel?.text = arrResponse[indexPath.row] as! String
    
            return cell
            }
    

    【讨论】:

    • @rmaddy 谢谢,更新了答案。
    • Alamofire.request(url, method: .get).responseJSON { 来自这一行本身的响应我 git 错误
    • 我遇到了如何通过调用值数组来调用请求的问题
    • @Agaram 我不明白你在说什么?
    • ["Mallard Point Trailer Court","Golddust","Hagler","McCosh Mill","Graystone","Old Jonesboro","Carlees Mobile Home Court","Denson"," Blake","Inverness Cliffs"] 这是响应..告诉我如何使用 alomofire 获取请求
    猜你喜欢
    • 2016-07-01
    • 1970-01-01
    • 2018-06-14
    • 1970-01-01
    • 1970-01-01
    • 2017-12-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多