简体   繁体   中英

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

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
            }
        })

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM