ios - Alamofire 和 Objectmapper 将数据添加到 TableView

标签 ios json swift alamofire objectmapper

    [
  {
    "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"]


    }
}

我的 View Controller 是这样的:

    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。数据即将到来,但我无法将其添加到 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"]
   }
}

你的 View Controller :

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<Schedule>().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
   }

}

关于ios - Alamofire 和 Objectmapper 将数据添加到 TableView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49321953/

相关文章:

ios - 升级到 Xcode 12.5 后的 xcodebuild 问题

ios - CFNetwork SSLHandshake 失败 (-9806) & (-9800) & (-9830)

JSON 解码器 无法读取数据,因为它的格式不正确

C# - Json 反序列化具有子属性的对象

ios - UI 选项卡栏 Controller 不显示设备上的所有选项卡。模拟器完美运行

ios - NSOperation 在后台任务结束之前完成

javascript - 每个 json 加载中的 Jquery.html 都不起作用

swift - 在命令行上使用 Swift 导入

ios - Swift - 分派(dispatch)到主队列足以使 var 线程安全吗?

swift - 如何在 View Controller 中显示触摸条