【发布时间】:2026-01-29 21:05:03
【问题描述】:
我目前正在将我的 json 数据发送到同一 ViewController 中的 Dictionary。我想将它发送到一个名为用户的类。数据显示在TableView 上。
import UIKit
class Users: NSObject {
var name: String?
}
class FriendsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var userList = [Users]()
@IBOutlet weak var myTableView: UITableView!
final let urlString = "https://api.lookfwd.io/v1/test/users"
var namesArray = [String]()
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return namesArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let myCell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! MyTableViewCell
myCell.nameLabel.text = namesArray[indexPath.row]
return myCell
}
override func viewDidLoad() {
super.viewDidLoad()
self.downloadJsonWithTask()
// Do any additional setup after loading the view.
}
func downloadJsonWithTask() {
let url = NSURL(string: urlString)
var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)
downloadTask.httpMethod = "GET"
URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in
let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)
if let dataArray = (jsonData! as AnyObject).value(forKey: "users") as? NSArray {
for data in dataArray{
// let user = Users()
// user.setValuesForKeys(data as! [String : Any])
// self.userList.append(user)
if let dataDict = data as? NSDictionary {
if let title = dataDict.value(forKey: "name") {
self.namesArray.append(title as! String)
}
}
print(jsonData!)
}
}
OperationQueue.main.addOperation({
self.myTableView.reloadData()
})
print(jsonData!)
}).resume()
}
}
【问题讨论】:
-
在将用户附加到 userList 之前,您需要将您的 json 转换为 User 模型。
-
你的问题不清楚。您是否尝试在一个视图控制器中执行 API 调用并希望在另一个控制器中显示数据?
-
不,我想将数据发送到我的用户类,然后在 FriendsViewController 的表格视图中显示名称
标签: ios json swift uitableview