How to get city/state/country of user using Facebook Graph API

588 views Asked by At

I am trying to populate textFields using FBSDKGraphRequest. First/last name and email are not a problem but when it comes to location all I can seem to do is get 'Austin, Texas'. I can't seem to get the individual values out and into textFields.

In the below code the city textField populates with 'Austin, Texas'. How would I be able to get just the city 'Austin' and then in a state textField get 'Texas'?

        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, first_name, last_name, location"]).start(completionHandler: { (connection, result, error) -> Void in
            if let error = error {
                self.alertTheUser(title: "Error", message: error.localizedDescription)
                print(error)
            }else{
                let fbDetails = result as! NSDictionary
                let location : NSDictionary! = fbDetails.value(forKey: "location") as! NSDictionary
                print(fbDetails)
                self.registerEmailField.text = fbDetails.value(forKey: "email") as? String
                self.registerFirstNameField.text = fbDetails.value(forKey: "first_name") as? String
                self.registerLastNameField.text = fbDetails.value(forKey: "last_name") as? String
                self.registerCityField.text = location.value(forKey: "name") as? String
            }
        })
1

There are 1 answers

0
Brandon On BEST ANSWER

Forgot to clear this one out.

The location in the FBSDKGraphRequest should be as below.

FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "email, first_name, last_name, location{location}"]).start(completionHandler: { (connection, result, error) -> Void in

You can then access the individual location values separately.

let locationContents: NSDictionary! = location.value(forKey: "location") as! NSDictionary
self.registerCityField.text = locationContents.value(forKey: "city") as? String
self.registerStateField.text = locationContents.value(forKey: "state") as? String
self.registerCountryField.text = locationContents.value(forKey: "country") as? String