ios - 将 NSArray 传递到 tableview swift 3.0

标签 ios swift uitableview

我正在尝试使用 php 将我的 swift ios 应用程序连接到 mysql...并且在从 php 接收到 JSON 后..我将其转换为 nsarray 并尝试用它填充我的 tableview..但是它似乎没有当我运行它时在 tableview 中显示任何内容......数据成功传递到 NSArray,因为我在打印(值)时看到我的结果......它似乎无法显示在我的 tableview 上而且我不知道为什么

@IBOutlet weak var tableView: UITableView!

var values:NSArray = []

@IBAction func php(_ sender: Any) {
    let url = NSURL(string: "http://localhost/try.php")
    let data = NSData(contentsOf: url! as URL)
    values = try! JSONSerialization.jsonObject(with: data! as Data, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSArray
    print (values)
    tableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return values.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

    cell.descriptionView.text = (values[indexPath.row] as AnyObject) as? String



    return cell
}

最佳答案

这是通过网络加载数据的推荐方式。

如评论中所述,不要在 Swift 3 中使用 NSArrayNSDataNSURLURLSession 加载异步和在后台的数据。 TableView 在主线程上重新加载。

var values = [[String:String]]()

@IBAction func php(_ sender: AnyObject) {
    let url = URL(string: "http://localhost/try.php")!
    let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
        if error != nil {
            print(error!)
            return
        }
        do {
            self.values = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String:String]]
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        } catch {
            print(error)
        }
    }
    task.resume()
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell
    let item = values[indexPath.row]
    cell.descriptionView.text = item["title"]
    return cell
}

关于ios - 将 NSArray 传递到 tableview swift 3.0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42055681/

相关文章:

iphone - 备份 2-4 个以前的 View

ios - 单个 Viewcontroller 中的多个 UITableview

ios - 当数据较少时,UITableview 中不会调用scrollViewDidEndDragging

objective-c - 在 iOS 中从 CoreData 获取数据的快速方法是什么?

iphone - TouchXML 命名空间解析?

cocoa-touch - UIModalPresentationFormSheet 呈现表上的键盘处理

objective-c - 后台应用程序 : NSAlert before shutdown

iphone - 如果 UIImagePickerControllerSourceTypePhotoLibrary 允许编辑 NO

swift - 创建框架和对成员 'log' 的模糊引用

ios - 基于 Stackview 高度的 tableview 单元格的动态高度