我正在尝试使用 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 中使用 NSArray
、NSData
和 NSURL
。URLSession
加载异步和在后台的数据。 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/