Alamofire and Objectmapper adding data to tableview

社会主义新天地 提交于 2019-12-05 06:40:57

问题


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

My json data is like that and I'm using alamofire for loading data and objectmapper for mapping.

I create a swift file for mapping like that:

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


    }
}

and my view controller like that:

    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)")

    }



}


}
}

I tried to print json data to TableView.Data is coming however I couldn't add it to tableview.What should I do to solve this problem ?


回答1:


You don't need TrainSchedules model.

Your model:

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

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

}



回答2:


There is a library called AlamofireObjectMapper https://github.com/tristanhimmelman/AlamofireObjectMapper

You can get Alamofire response as ObjectMapper objects and then pass use this result for showing data in tableview.



来源:https://stackoverflow.com/questions/49321953/alamofire-and-objectmapper-adding-data-to-tableview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!