Search code examples
jsonswiftnsurlrequest

Parse JSON output from AlamoFire


I am using the latest Alamofire to manage a GET http request to my server. I am using the following to GET and parse the JSON:

 Alamofire.request(.GET, "*******")
            .responseJSON {(request, response, JSON, error) in

                if let statusesArray = JSON as? NSArray{
                    if let aStatus = statusesArray[0] as? NSDictionary{

                        //OUTPUT SHOWN BELOW
                        println( "BREAKING DOWN \(aStatus)")

                        // This doesn't output anything?????
                        if let user = aStatus["title"] as? NSDictionary{
                            println( "TITLE \(user)")
                        }


                    }
                }

                println(JSON)

        }

The GET request works and the issue I am facing is attempting to target the title key in the JSON output. The println doesn't output anything. I could easily do this in objective C but for some reason SWIFT is confusing me. The output from the println

BREAKING DOWN {
    "__v" = 0;
    "_id" = 5588468c65340938150f674f;
    endDate = 1435004396596;
    fullDescription = "Neutra blog McSweeney's pug Austin, put a bird on it fanny pack. Try-hard jean shorts trust fund vinyl kale chips, blog distillery pickled synth. Tofu fap Intelligentsia umami, McSweeney's pork belly church-key literally roof party crucifix lumbersexual meditation irony four loko. Mlkshk tousled before they sold out pork belly. PBR&B craft beer Tumblr, trust fund swag chillwave Truffaut.Retro cray narwhal 3 wolf moon. Pug master cleanse dreamcatcher, Vice Blue Bottle next level Helvetica messenger bag distillery chillwave pickled tattooed wayfarers DIY cold-pressed.";
    shortDescription = "Neutra blog McSweeney's pug Austin, put a bird on it fanny pack.";
    startDate = 1434994316596;
    title = "Artisanal Yoghurt";
}

Solution

  • If I believe the println of aStatus, the property title is a String, not a Dictionary.

    Change this part in your code (cast as String instead of as NSDictionary):

    if let user = aStatus["title"] as? String {
        println( "TITLE \(user)")
    }