【问题标题】:How to map objects with Alamofire->4.0 in swift 3如何在swift 3中使用Alamofire-> 4.0映射对象
【发布时间】:2017-12-16 09:04:02
【问题描述】:

我是 Swift 编程语言的新手,我必须在 Swift 3 中使用 Alamofire 4.0 映射对象,并遵循相同的链接>https://github.com/tristanhimmelman/AlamofireObjectMapper

但是当我复制粘贴下面的代码时,我得到了nil 响应,有人可以帮助我了解如何使用 GETPOST 方法映射模型对象吗?

代码:-

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        let URL = "https://raw.githubusercontent.com/tristanhimmelman/AlamofireObjectMapper/2ee8f34d21e8febfdefb2b3a403f18a43818d70a/sample_keypath_json"

        Alamofire.request(URL).responseObject { (response: DataResponse<WeatherResponse>) in

            switch(response.result) {

            case .success(_):

                if response.result.value != nil{

                    let weatherResponse = response.result.value

                    print("response is========>\(weatherResponse?.location))")

                    if let threecatForday = weatherResponse?.threeDayForecast{

                        for forCast in threecatForday{
                            print("Day is======>\(forCast.day)")
                            print("Tempurature======>\(forCast.temperature)")
                        }
                    }

                }
                break

            case .failure(_):
                print(response.result.error!)
                break
            }
        }
    }
}

天气响应:-

import UIKit
import ObjectMapper

class WeatherResponse: Mappable {

    var location: String?
    var threeDayForecast: [Forecast]?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        location <- map["location"]
        threeDayForecast <- map["three_day_forecast"]
    }
}

预测:-

import UIKit
import ObjectMapper

class Forecast: Mappable {

    var day: String?
    var temperature: Int?
    var conditions: String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        day <- map["day"]
        temperature <- map["temperature"]
        conditions <- map["conditions"]
    }
}

【问题讨论】:

  • 对于 GET 你可以使用这样的东西: Alamofire.request(URL, method: .get, parameters: nil, encoding: URLEncoding.default).responseObject { (response: DataResponse) in对于 POST:Alamofire.request(URL, method: .post, parameters: nil, encoding: URLEncoding.default).responseObject { (response: DataResponse) in...
  • 好的,谢谢您的回复
  • 你能回答这个问题吗

标签: swift alamofire objectmapper


【解决方案1】:

您的WeatherResponse 模型缺少data 节点

使用这个模型

class WeatherResponse: Mappable {

    var data: WeatherResponseData?

    required init?(map: Map){ }

    func mapping(map: Map) {
        data <- map["data"] // data
    }
}


class WeatherResponseData: Mappable {

    var location: String?
    var threeDayForecast: [Forecast]?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        location <- map["location"]
        threeDayForecast <- map["three_day_forecast"]
    }
}


class Forecast: Mappable {

    var day: String?
    var temperature: Int?
    var conditions: String?

    required init?(map: Map) {

    }

    func mapping(map: Map) {
        day <- map["day"]
        temperature <- map["temperature"]
        conditions <- map["conditions"]
    }
}

然后打印结果

print("response is========>\(weatherResponse?.data?.location))")

【讨论】:

    【解决方案2】:

    在 Swift 3 Alamofire 中

    您也可以使用此方法传递参数

    使用 Alamofire 首次获取请求

    let strUrl = " Your URL here "
    let parameter:Parameters = ["user_id":"2","isdelete": "0" ,"status":"0","page":pageindex ,"limit":"9"]
    Alamofire.request(strUrl, method : .post, parameters: parameter).responseJSON{response in
        let result = response.result
        if let dict = result.value as? Dictionary<String,AnyObject>{
            if let innerDict = dict["orders"]{
    
                self.array.addObjects(from: innerDict as! [Any]);
    
                DispatchQueue.main.async {
                    self.tblView.reloadData()
                    self.refresh.endRefreshing()
                }
            }
        }
    }
    

    然后像这样传递具体 就我而言,我需要在 UITableViewCell 中显示这一点

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
        let cell = tblView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? CustomTableViewCell
        let title = (array.object(at: indexPath.row) as! NSDictionary).value(forKey: "created_at") as! String
        let category = (array.object(at: indexPath.row) as! NSDictionary).value(forKey: "orderno") as! String
        //print(title)
        cell?.lblName.text = title
        cell?.lblCategory.text = category
        cell?.layer.borderWidth = 2.0
        cell?.layer.borderColor = UIColor.gray.cgColor
        if (indexPath.row == self.array.count - 1) && (self.array.count % 9 == 0) {
            print("End Of the Page")
            pageindex += 1
            print(pageindex)
            Loaddata()
    
        }
        return cell!
    }
    

    希望这会有所帮助

    谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-20
      • 2017-12-16
      • 2017-02-16
      • 2016-05-13
      • 2017-11-03
      • 2018-03-01
      • 1970-01-01
      • 2017-11-28
      相关资源
      最近更新 更多