1

I want to convert the friend list ids that I am getting from facebook as an array to save in parse. My code is as below but I am getting a "unexpectedly found nil while unwrapping an Optional value" error. What should I do to save the result to parse and retrieve it as array when required?

  let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
                fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in

                    if error == nil {

                        print("Friends are : \(result)")

                        if let dict = result as? Dictionary<String, AnyObject>{

                            let profileName:NSArray = dict["name"] as AnyObject? as! NSArray
                            let facebookID:NSArray = dict["id"] as AnyObject? as! NSArray

                            print(profileName)
                            print(facebookID)

                    }

                    }
                        else {

                        print("Error Getting Friends \(error)");

                    }
                }

When I use the code below in print() I get the result below:

 Friends are : {
data =     (
            {
        id = 138495819828848;
        name = "Michael";
    },
            {
        id = 1105101471218892;
        name = "Johnny";
    }
);
saner
  • 821
  • 2
  • 10
  • 32

1 Answers1

5

The issue is that you are trying to access the name and id elements from the top-level dictionary, where you need to be accessing data.

When you call the FB Graph API for friends it will return an array of dictionaries (one per friend).

Try this:

let fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil)
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in

    if error == nil {

        print("Friends are : \(result)")

        if let friendObjects = result["data"] as? [NSDictionary] {
            for friendObject in friendObjects {
                println(friendObject["id"] as NSString)
                println(friendObject["name"] as NSString)
            }
        }
    } else {
        print("Error Getting Friends \(error)");
    }
}

You should also check out this SO post with more information on the FB Graph API. Here's a brief snippet.

In v2.0 of the Graph API, calling /me/friends returns the person's friends who also use the app.

In addition, in v2.0, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends. See the Facebook upgrade guide for more detailed information, or review the summary below.

Russell
  • 3,099
  • 2
  • 14
  • 18