13

I have integrated the FB latest SDK(non-swift) and log in is working fine. All I need to know how do I parse the Graph response data since its not a valid JSON

Working code:

     func configureFacebook()
        {
            login.readPermissions = ["public_profile", "email", "user_friends"];
            login.delegate = self
        }


func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
    print("Login buttoon clicked")
    let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])

    graphRequest.start(completionHandler: { (connection, result, error) -> Void in

        if ((error) != nil)
        {
            // Process error
            print("Error: \(error)")
        }
        else
        {
            print(result)

        }
    })
}

With output:

Login button clicked
Optional({
    "first_name" = KD;
    id = 10154CXXX;
    picture =     {
        data =         {
            "is_silhouette" = 0;
            url = "https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/XXXn.jpg?oh=a75a5c1b868fa63XXX146A";
        };
    };
})

So what format should I convert the above data to get values like URL or first_name etc?

Also I tried converting to NSDictionary and got error:

func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        print("Login buttoon clicked")
        let graphRequest:FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name,email, picture.type(large)"])

        graphRequest.start(completionHandler: { (connection, result, error) -> Void in

            if ((error) != nil)
            {
                print("Error: \(error)")
            }
            else
            {
                do {

                let fbResult = try JSONSerialization.jsonObject(with: result as! Data, options: JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
                print(fbResult.value(forKey: "name"))


                } catch {
                    print(error)
                }

            }
        })
    }

2 Answers 2

21

You can simply do it as follows:

let data:[String:AnyObject] = result as! [String : AnyObject]
print(data["first_name"]!)

Swift 3:

Safe unwrapping & Any instead of AnyObject

if let data = result as? [String:Any] {

}
4
  • 4
    This seems to be the simplest. Final code for me. let data:[String:AnyObject] = result as! [String : AnyObject] let urlData = data["picture"]?.value(forKey: "data") as! [String : AnyObject] let url = urlData["url"]!
    – KD.
    Sep 8, 2016 at 8:58
  • Tried access profile picture like earlier, but now nil returned even though info is there: let profilePictureURLStr = data["picture.data.url"] as? String. Something wrong.
    – János
    Oct 2, 2016 at 16:59
  • Are you using swiftyJSON?
    – Bista
    Oct 2, 2016 at 17:01
  • Could you check my problem with code here: stackoverflow.com/questions/39325970/…
    – János
    Oct 2, 2016 at 17:53
1

Swift 5 Code for question and issue and solution:

Implementation:

let graphRequest:GraphRequest = GraphRequest(graphPath: "me", parameters: ["fields":"first_name,email,picture.type(large)"])
graphRequest.start(completionHandler: { (connection, result, error) -> Void in
    if ((error) != nil) {
        print("Error: \(String(describing: error))")
    }
    else {
        guard let rDic = result as? NSDictionary else {
            SVProgressHUD.showError(withStatus: "facebook Did not allowed loading email, please set that while updating profile.")
            return
        }
        print("rDic = ", rDic)
    }
})

Output:

rDic =  {
    email = "[email protected]";
    "first_name" = Mr. Me;
    id = #################;
    picture =     {
        data =         {
            height = 32;
            "is_silhouette" = 0;
            url = "https://platform-lookaside.fbsbx.com/platform/profilepic/?asid=################&height=200&width=200&ext=################&hash=################";
            width = 32;
        };
    };
}

P.S.: Thanks to KD and Bista their question and answer helped me figure this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.