我正在尝试通过使用 PHP 从外部数据库中获取数据来加载表。我在服务器上有脚本,并且能够获取数据。我试图获得帮助并理解逻辑,但我仍然无法理解。
目前,我只设置了我的 tableview,但没有数据。
请让我知道如何获取数据。
谢谢
代码:
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var group = [Group]()
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
// cell.textLabel?.text = myarray[indexPath.item]
return cell
}
}
代码:(我怎样才能在表格视图上显示数据)?
import UIKit
class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
//let myarray = ["item1", "item2", "item3"]
var group = [Group]()
@IBOutlet weak var tableview: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "http://www.myurl/myfile.php")
let task = URLSession.shared.dataTask(with: url! as URL) { data, response, error in
guard let data = data, error == nil else { return }
print(NSString(data: data, encoding: String.Encoding.utf8.rawValue))
}
task.resume()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
tableview.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//return myarray.count
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "groupCell", for: indexPath) as! UITableViewCell
// cell.textLabel?.text = myarray[indexPath.item]
return cell
}
}
您需要使用以下代码根据您的响应创建一个数组或字典
您需要将字符串传递给您在打印语句中使用的这些函数。
如果响应作为字典返回
func convertToDictionary(text: String) -> [String: Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
从字典中获取数组以与 tableview 绑定。
如果响应作为数组返回
func convertToArray(text: String) -> [Any]? {
if let data = text.data(using: .utf8) {
do {
return try JSONSerialization.jsonObject(with: data, options: []) as? [Any]
} catch {
print(error.localizedDescription)
}
}
return nil
}
然后将此数组中的数据绑定到 tableView。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句