clicky clicky - 29 days ago 12
Swift Question

Facebook graph object/entity parsing SDK 4 in Swift

In Swift how do you parse the result of a fbk graph request? I have a nested dictionary and casting to [String: String] does not work. I have casted to NSDictionary which works for level 1 but anything nested started complaining about optionals and casting. I see from the changeling that FBGraphObject has been deprecated, so what is the correct approach now in SDK 4?

My data looks like

{
data = {
"is_silhouette" = 0;
url = "...";
};
}


I can do

var data = photoRes["data"] as? NSDictionary


to get

Optional({
"is_silhouette" = 0;
url = "...;
})


I'm not sure how to parse that object...

EDIT For now I have it working with

var data = photoRes["data"] as? NSDictionary
var urlStr = data!["url"] as? String
if urlStr != nil {
let url = NSURL(fileURLWithPath: urlStr!)
//my code...
}


But this is a complicated approach especially if the result coming back is highly nested. Is there a better way to go about this?

Answer

Create a dictionary :

class ViewController: UIViewController {
    var dict : NSDictionary!
}

Fetching the data :

if((FBSDKAccessToken.currentAccessToken()) != nil){
    FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, picture.type(large), email"]).startWithCompletionHandler({ (connection, result, error) -> Void in
        if (error == nil){
            self.dict = result as NSDictionary               
            println(self.dict)
            NSLog(self.dict.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as String)
        }
    })
}

Output should be :

{
    email = "ashishkakkad8@gmail.com";
    "first_name" = Ashish;
    id = 910855688971343;
    "last_name" = Kakkad;
    name = "Ashish Kakkad";
    picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab";
        };
    };
}
2015-05-25 22:12:34.015 SwiftFB[2713:7830] https://fbcdn-profile-a.akamaihd.net/hprofile-ak-xfa1/v/t1.0-1/s200x200/22501_915701971820048_9046303472199214595_n.jpg?oh=f3b3564f1450c13332b3067a135cad5d&oe=55C71792&__gda__=1443571904_c4667dcb08d85682edfd77a90ee9c3ab