Search code examples
swiftxcodefbsdk

Issue with FBSDKGraphRequest using the result object


I'm having issues with the Facebook SDK, (swift 4, Xcode 9) after the user login successfully, im trying to pull back some details about the users account like their email address, name and picture.

But the code below give's me a complier error on this line

if let email = result["email"] as? String

This is the error i'm getting.

Value of optional type 'Any?' not unwrapped; did you mean to use '!' or '?'?

Here is the full function that has the code to fetch the users profile info. I've tried many various of testing for the optional, using '!' but all result in complier errors.

func fetchProfile() {
        print("in fetch profile")

        let parameters = ["fields": "email, first_name, last_name, picture.type(large)"]
        FBSDKGraphRequest(graphPath: "me", parameters: parameters).start { (connection, result, error) -> Void in

            print("In FBSDKGraphRequest")

            print(result)
            if error != nil {
                print(error as Any)
                return
            }

            if let email = result["email"] as? String
            {
                print(email)
            }
        }
    }

Any help appreciated.


Solution

  • Usually the result can be interpreted as a swift dictionary [String: Any]. So you can try cast the result to [String: Any] and then try to take the email as a String.

    if let result = result as? [String: Any] {
        if let email = result["email"] as? String {
             print(email)
        }
    }