【发布时间】:2018-10-28 13:31:20
【问题描述】:
我的服务器上有一个 php 脚本,它只是一个基本的 sql SELECT 语句,它从 mysql 数据库中获取一些数据并返回一些行。
我使用 alamofire 和 swiftyjson 将数据打印到控制台,但我想在表格视图中显示它。
由于调用与 tableView 代码不在同一范围内(我认为这就是我收到错误消息“使用未解析的标识符”的原因)
我不确定如何使其成为全局变量,但我想我需要创建一个全局数组变量,但不确定它是否应该为空?
全局:
let serviceURL = "http://example.com/service.php"
我把它放在这样的函数中:
func getUsers() {
Alamofire.request(serviceURL, method: .get).validate().responseJSON { (response) in
if response.result.isSuccess {
let userJSON : JSON = JSON(response.result.value!)
for (index,subJson):(String, JSON) in userJSON {
let firstName = subJson["first_name"].string
let lastName = subJson["last_name"].string
print(firstName)
}
} else {
print("Could not get results")
}
}
}
我需要以某种方式计算返回的行数
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return firstName.count
}
然后实际显示在单元格中
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
cell.textLabel?.text = names[indexPath.row]
return cell
}
更新
import UIKit
import Alamofire
import SwiftyJSON
struct User {
var firstName: String
var lastName: String
private enum CodingKeys: String, CodingKey {
case firstName = "first_name"
case lastName = "last_name"
}
}
class UserTableViewController: UITableViewController {
var users = [User]()
let serviceURL = "http://example.com/service.php"
override func viewDidLoad() {
super.viewDidLoad()
getUsers()
}
func getUsers() {
Alamofire.request(serviceURL, method: .get).validate().responseJSON { (response) in
if response.result.isSuccess {
let userJSON : JSON = JSON(response.result.value!)
for (index,subJson):(String, JSON) in userJSON {
let firstName = subJson["first_name"].string
let lastName = subJson["last_name"].string
let user = User(firstName: firstName!, lastName: lastName!)
self.users.append(user)
}
} else {
print("Could not get results")
}
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return users.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "userCell", for: indexPath)
let user = users[indexPath.row]
cell.textLabel?.text = "\(user.firstName) \(user.lastName)"
return cell
}
}
【问题讨论】:
-
names数组包含什么?为什么不在getUsers和tableView:numberOfRowsInSection中使用这个数组? -
抱歉,名称来自我刚刚创建一个数组以在使用 alamofire 等之前将数据放入表中。它只是一个像这样的数组:
let names = ["Bob", "Judy", "Tony"]但我现在需要它包含数据库中的数据
标签: ios swift swift4 alamofire swifty-json