简体   繁体   English

Alamofire和Objectmapper向表视图添加数据

[英]Alamofire and Objectmapper adding data to tableview

    [
  {
    "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. 我的json数据就是这样,我正在使用alamofire加载数据并使用objectmapper进行映射。

I create a swift file for mapping like that: 我创建了一个用于映射的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"]


    }
}

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 ? 我试图将json数据打印到TableView.Data即将到来,但是我无法将其添加到tableview中。我该怎么办才能解决此问题?

You don't need TrainSchedules model. 您不需要TrainSchedules模型。

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: 您的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
   }

}

There is a library called AlamofireObjectMapper https://github.com/tristanhimmelman/AlamofireObjectMapper 有一个名为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. 您可以将Alamofire响应作为ObjectMapper对象获得,然后使用此结果在表视图中显示数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM