2

in my app i am first time using AlamofireObjectMapper. So i am mapping api response data in one class and then i want to use that data. So here is my code that how i map object

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

    }
}

and here is the class where i saving my data

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

    }

}

now in my OrderListViewController i want to use this data so how can i use this??

    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

    }
}

for example i want to print message value in my tableview cell label. so how can i get that value form OrderList?

Thanks slava its give me some solution. but my json response give me array. So how can i manage it? and i want to return in numberofrowinSetcion is count of array so how can i do this. please see my updated question.

here is my api response.

    {
    "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"
        }
    ]
}
Jack.Right
  • 974
  • 3
  • 14
  • 30
  • Note as for code style: it is common practice to use names for local variables starting from lower letter (not from capital one). So my advise is to use `var message: String!` instead of `var Message: String!`. Though at the end it is entirely up to you which style to use. – slava May 17 '16 at 06:29

2 Answers2

1

You need a local variable in your controller to store all the received information that will be used to fill the table. Something like that should do:

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

Note: the code should be correct in case you receive the single object in JSON from backend. If backend sends the array of objects - you'll need to use array to store local data (private var listOfOrderLists: [OrderList]) and use Alamofire.request(...).responseArray(...) instead. But the idea about local variable is still the same.

slava
  • 377
  • 5
  • 11
  • Thanks slava its give me some solution. but my json response give me array. So how can i manage it? and i want to return in numberofrowinSetcion is count of array so how can i do this. please see my updated question. – Jack.Right May 17 '16 at 07:10
  • I've updated the code in the answer, hope that will help – slava May 17 '16 at 07:37
  • Damn! Perfect man its working pretty well and even its clear my all doubts. Thanks man its really helpful. i am going to upvote and marking as right. so others can also get the help. – Jack.Right May 17 '16 at 07:54
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

    }
}
Ankush Dhawan
  • 319
  • 1
  • 3
  • 5