【问题标题】:Alamofire and Objectmapper adding data to tableviewAlamofire 和 Objectmapper 将数据添加到 tableview
【发布时间】:2018-08-25 14:12:48
【问题描述】:
    [
  {
    "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。数据来了,但是我无法将它添加到 tableview。我应该怎么做才能解决这个问题?

【问题讨论】:

    标签: ios json swift alamofire objectmapper


    【解决方案1】:

    有一个库叫AlamofireObjectMapperhttps://github.com/tristanhimmelman/AlamofireObjectMapper

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

    【讨论】:

      【解决方案2】:

      您不需要 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"]
         }
      }
      

      你的视图控制器:

      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
         }
      
      }
      

      【讨论】:

      • 是的,它有效,我理解。但是我不明白为什么即使我可以使用标题和正文,我也不能连续显示 userId 或 id。
      • 非常感谢这个例子,我在 Stack 和其他地方看到了很多教程 cmets 和答案,没有人建议做“response in self.schedules = Mapper ().mapArray(JSONObject: response.result.value)" 这个,非常感谢你的帮助,这表明现在 swift 社区有多低...
      猜你喜欢
      • 1970-01-01
      • 2020-11-27
      • 2018-12-23
      • 2018-11-09
      • 1970-01-01
      • 2020-04-07
      • 2016-09-20
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多