如何访问其他Mappble类对象的值。(Alamofire Object Mapper)

时间:2016-05-17 05:37:20

标签: ios swift mapping alamofire objectmapper

在我的应用程序中我第一次使用AlamofireObjectMapper。 所以我在一个类中映射api响应数据然后我想使用该数据。 所以这是我的代码,我如何映射对象

    extension OrderListViewController
{
 func get_order_list()
  {


        let url = "\(OrderURL)get_New_order_byPharmacy"
        let param : [String : AnyObject] = [

            "pharmacyId" : "131"
        ]

        Alamofire.request(.GET, url, parameters: param, encoding: .URL).responseObject { (response:Response<OrderList, NSError>) in
            let OrderList = response.result.value
            print(OrderList!.Message)
        }

    }
}

这是我保存数据的类

    class OrderList: Mappable {
    var Message : String!
    var Status : Int!
    var result:[OrderResult]?



    required init?(_ map: Map){

    }

    func mapping(map: Map) {
        Message <- map["Message"]
        Status <- map["Status"]
        result <- map["Result"]

    }

}

现在在我的OrderListViewController中我想使用这个数据,所以我该如何使用它?

    class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var table_OrderList: UITableView!


    override func viewDidLoad() {
        slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
        slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
        get_order_list()
    }


    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell



        return cell

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 20

    }
}

例如我想在tableview单元格标签中打印消息值。那么如何从OrderList中获取该值?

谢谢slava给我一些解决方案。但我的json响应给了我数组。那我该怎么办呢?我想返回numberofrowinSetcion是数组的数量,所以我该怎么做。请看我更新的问题。

这是我的api回复。

    {
    "Status": 1,
    "Message": "records are available",
    "Result": [
        {
            "id": 30162,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-11T10:45:00.6779848",
            "created": "11 May 2016"
        },
        {
            "id": 30170,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-12T07:01:00.6968385",
            "created": "12 May 2016"
        },
        {
            "id": 30171,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-12T09:12:53.5538349",
            "created": "12 May 2016"
        },
        {
            "id": 30172,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-12T09:46:09.4329398",
            "created": "12 May 2016"
        },
        {
            "id": 30173,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-12T11:26:58.3211678",
            "created": "12 May 2016"
        },
        {
            "id": 30178,
            "status_id": 2,
            "status_type": "New Order",
            "created_date": "2016-05-16T07:34:19.9128517",
            "created": "16 May 2016"
        }
    ]
}

2 个答案:

答案 0 :(得分:1)

您需要控制器中的局部变量来存储将用于填充表格的所有已接收信息。这样的事情应该做:

class OrderListViewController: ... {
    private var orderList: OrderList? // <- the local variable needed
    ...
}

extension OrderListViewController {
    func get_order_list() {
        ...
        Alamofire
            .request(...)
            .responseObject { (response:Response<OrderList, NSError>) in
                switch response.result {
                case .Success(let value):
                    self.orderList = value // <- fill the local variable with the loaded data
                    self.tableView.reloadData()
                case .Failure(let error):
                    // handle error
                }
            }
    }
    ...
}

extension OrderListViewController: UITableViewDataSource {
    ...
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell
        // I assume 'OrderList_Cell' class has outlet for status type named 'statusTypeLabel' and OrderResult.statusType is of type String
        if let orderList = orderList, orderResults = orderList.result {
            cell.statusTypeLabel.text = orderResults[indexPath.row].statusType // <- use of the locally stored data
        }

        return cell
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let orderList = orderList, orderResults = orderList.result {
            return orderResults.count
        } else {
            return 0
        }
    }
}

注意:如果您从后端收到JSON中的单个对象,则代码应该是正确的。 如果后端发送对象数组 - 您需要使用数组来存储本地数据(private var listOfOrderLists: [OrderList])并使用Alamofire.request(...).responseArray(...)代替。但关于局部变量的想法仍然是一样的。

答案 1 :(得分:0)

typealias FailureHandler = (error: AnyObject) -> Void
typealias SuccessHandler = (result: AnyObject)  -> Void 
class WebServiceManager: NSObject {

    class func getDataFromService(mehodName:String,success:(result:AnyObject)->(), apiError:(FailureHandler))
    {
         let url = "\(OrderURL)get_New_order_byPharmacy"
        let param : [String : AnyObject] = [

            "pharmacyId" : "131"
        ]

         alamoFireManager!.request(.GET, url)
            .responseJSON { response in
            print(response.response!)
                print(response.result)
                CommonFunctions.sharedInstance.deactivateLoader()
                switch response.result {
                case .Success(let JSON):
                    print("Success with JSON: \(JSON)")

                    guard let _ = JSON as? NSMutableArray else {
                        apiError(error: "")
                        return
                    }
                    let listOfItem:NSMutableArray = NSMutableArray()

                    for (_, element) in adsArray.enumerate() {
                        let adsItem = Mapper<OrderList>().map(element)
                    listOfItem.addObject(adsItem!)
                    }


                    success(result:listOfItem)



                case .Failure(let data):
                    print(data)






                }



        }

}


 class OrderListViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

    @IBOutlet weak var table_OrderList: UITableView!
    var listOFOrder:NSMutableArray =[]

    override func viewDidLoad() {
        slideMenuController()?.addLeftBarButtonWithImage(UIImage(named: "ic_menu_black_24dp")!)
        slideMenuController()?.addRightBarButtonWithImage(UIImage(named: "ic_notifications_black_24dp")!)
 WebServiceManager.getDataFromService("", success: { (result) in
            listOFOrder = result as NSMutableArray
            self.recordTable?.reloadData()
            }) { (error) in

        }




    }


    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    }

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell : OrderList_Cell = tableView.dequeueReusableCellWithIdentifier("OrderList_Cell") as! OrderList_Cell



        return cell

    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listOFOrder.count

    }
}