Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to serialize json response to dictionary in alamofire 2 with swift 2 without swifty json

Tags:

alamofire

This code used to work in the previousversion of alamofire before swift 2. Now it gives a warning: cast from Result<AnyObject> to Dictionary<String, AnyObject> always fails.

  Alamofire.Manager.sharedInstance.request(.POST, url, parameters:params)
            .responseJSON { (request, response, data) -> Void in

            var result = data as? Dictionary<String,AnyObject> //this gives an error cast from Result<AnyObject> to Dictionary<String, AnyObject> always fails

How can I get the cast to dictionary working?

like image 449
MonkeyBonkey Avatar asked Sep 14 '15 03:09

MonkeyBonkey


2 Answers

You need to call:

Alamofire.request(.POST, url, parameters:params)
    .responseJSON { request, response, result in
        debugPrint(result)

        if let value = result.value as? [String: AnyObject] {
           print(value)
        }
    }

You should read through the updated README code samples.

like image 94
cnoon Avatar answered Sep 24 '22 17:09

cnoon


I know it's bit too late to answer this but I share this because I feel like maybe this code can help someone:

Alamofire.request(url, method: .post, parameters: param, encoding: JSONEncoding.default, headers: nil).responseJSON
            {
                response in

                SVProgressHUD.dismiss()

                let data = response.result.value

                let responseObject = data as? NSDictionary

                switch (response.result)
            {
                case .success(_):

                print(responseObject!["message"] as! NSString as String)
                break

                case .failure(_):
                   SVProgressHUD.showError(withStatus: (responseObject!["message"] as! NSString as String))
                print(responseObject!["message"] as! NSString as String)
                break
            }
        }

Thanks and Enjoy! Happy coding! :)

like image 44
iHarshil Avatar answered Sep 21 '22 17:09

iHarshil