如何在swift 3中使用Alamofire-> 4.0映射对象

时间:2017-07-12 05:32:45

标签: swift alamofire objectmapper

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

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

代码: -

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

WetherResponse: -

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

2 个答案:

答案 0 :(得分:0)

您的WeatherResponse模型缺少data节点

enter image description here

使用此模型

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

答案 1 :(得分:0)

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

希望这应该有所帮助

谢谢