Alamofire和Objectmapper将数据添加到tableview

时间:2018-03-16 13:27:45

标签: 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"]


    }
}

和我的视图控制器一样:

    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。我应该怎么做才能解决这个问题?

3 个答案:

答案 0 :(得分: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"]
   }
}

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

}

答案 1 :(得分:0)

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

使用
import UIKit
import Alamofire

class ViewController: UIViewController {

     @IBOutlet weak var tableView: UITableView!

     var titleArray = [String]()
     var userIdArray = [Int]()

    override func viewDidLoad() {
    super.viewDidLoad()

     getData()
    }

 }

使用Alamofire从api获取数据

extension ViewController {

func getData() {
    Alamofire.request("https://jsonplaceholder.typicode.com/posts", method: .get, parameters: nil, encoding: URLEncoding.default, headers: nil).responseJSON { (response:DataResponse<Any>) 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

        }
    }

  }
}

UITableView数据源和委托方法

extension ViewController: UITableViewDataSource, UITableViewDelegate {
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
}
}

UITableViewCell类

class tableCell: UITableViewCell {

@IBOutlet weak var nameLabel: UILabel!

}

答案 2 :(得分:0)

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

的图书馆

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