2

在我的应用程序中,我第一次使用 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"
        }
    ]
}
4

2 回答 2

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(...)改用。但是关于局部变量的想法仍然是一样的。

于 2016-05-17T06:20:22.993 回答
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

    }
}
于 2016-05-17T06:28:23.713 回答