Alamofire和Objectmapper将数据添加到tableview

[ { "userId": 1, "id": 1, "title": "xxxxx", "body": "yyyyy" }, { 

我的json数据是这样的,我使用alamofire加载数据和objectmapper进行映射。

我创建一个swift文件进行映射,如下所示:

  import Foundation import ObjectMapper class TrainSchedules: Mappable { var mySchedules: [Schedules] required init?(map: Map) { mySchedules = [] } func mapping(map: Map) { mySchedules <- map["schedule"] } } class Schedules: Mappable { var userId: String var id: String var title: String var body: String required init?(map: Map) { userId = "" id = "" title = "" body = "" } func mapping(map: Map) { userId <- map["userId"] id <- map["id"] title <- map["title"] body <- map["body"] } } 

我的视图控制器是这样的:

  import Alamofire import ObjectMapper class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = "Landmark" return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } @IBOutlet weak var tableViewData: UITableView! override func viewDidLoad() { super.viewDidLoad() tableViewData.dataSource = self tableViewData.delegate = self let jsonDataUrl = "https://jsonplaceholder.typicode.com/posts" Alamofire.request(jsonDataUrl).responseJSON { response in print("Request: \(String(describing: response.request))") print("Response: \(String(describing: response.response))") print("Result: \(response.result)") if let json = response.result.value { print("JSON: \(json)") } if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") } } } } 

我试图将json数据打印到TableView.Data即将到来,但我无法将其添加到tableview。我应该怎么做才能解决这个问题?

您不需要TrainSchedules模型。

你的型号:

 import Foundation import ObjectMapper class Schedule: Mappable { var userId: String var id: String var title: String var body: String required init?(map: Map) { userId = "" id = "" title = "" body = "" } func mapping(map: Map) { userId <- map["userId"] id <- map["id"] title <- map["title"] body <- map["body"] } } 

你的ViewController:

 import Alamofire import ObjectMapper import UIKit class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var tableViewData: UITableView! var schedules: [Schedule]? override func viewDidLoad() { super.viewDidLoad() tableViewData.dataSource = self tableViewData.delegate = self loadData() } func loadData() { let jsonDataUrl = "https://jsonplaceholder.typicode.com/posts" Alamofire.request(jsonDataUrl).responseJSON { response in self.schedules = Mapper().mapArray(JSONObject: response.result.value) self.tableViewData.reloadData() } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() cell.textLabel?.text = schedules?[indexPath.row].title return cell } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return schedules?.count ?? 0 } } 

你可以简单地使用这个,如果这是获得api然后在后期使用: –

  import UIKit import Alamofire class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var titleArray = [String]() var userIdArray = [Int]() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. alamofire() } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return titleArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! tableCell cell.nameLabel.text = titleArray[indexPath.row] return cell } func alamofire() { Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse) in switch(response.result) { case .success(_): guard let json = response.result.value as! [[String:Any]]? else{ return} print("Response \(json)") for item in json { if let title = item["title"] as? String { self.titleArray.append(title) } if let userID = item["userId"] as? Int { self.userIdArray.append(userID) } DispatchQueue.main.async { self.tableView.reloadData() } } break case .failure(_): print(response.result.error as Any) break } } } } class tableCell: UITableViewCell { @IBOutlet weak var nameLabel: UILabel! } 

有一个名为AlamofireObjectMapper的库https://github.com/tristanhimmelman/AlamofireObjectMapper

您可以将Alamofire响应作为ObjectMapper对象,然后通过使用此结果在tableview中显示数据。