slimboy
slimboy

Reputation: 1653

How to write Facebook Graph Request for the new swift 3?

I'm trying to use the new FacebookSdk for Swift3, but I can't figure out how to accomplish a simple Graph request. I definitely have it all wrong. this is what I have below. has anyone figured it out?

    import FacebookCore
    import FacebookLogin
    import FacebookShare



    let parameters = ["fields": "id, name, gender, picture.width(300).height(300).type(large).redirect(false)"]
                let nextrequest: GraphRequest = GraphRequest(graphPath: "me", parameters: parameters, accessToken: AccessToken.current, httpMethod: GraphRequestHTTPMethod(rawValue: "GET")!)


                nextrequest.start({ (response: HTTPURLResponse?, result: GraphRequestResult<GraphRequest>) in



                    if error != nil {
                    }

if let name = result["name"] as? String, let id = result["id"] as? String, let gender = result["gender"] as? String {
                   print(name)
                   print(id)
                   print(gender)
 } 
else {}
                })

Upvotes: 0

Views: 1872

Answers (3)

Harjot Singh
Harjot Singh

Reputation: 6927

Update for > Swift 4:

Facebook SDK Version: 4.33.0

@IBAction func btnLoginWithFacebook(_ sender: Any) {
    let loginManager = LoginManager()
    loginManager.logIn(readPermissions: [.publicProfile, .email, .userBirthday, .userGender, .userLocation], viewController: self, completion: { loginResult in
        switch loginResult {
        case .failed(let error):
            print(error)
        case .cancelled:
            print("User cancelled login.")
        case .success(let grantedPermissions, let declinedPermissions, let accessToken):
            self.getFbId()
            print("Logged in! \(grantedPermissions) \(declinedPermissions) \(accessToken)")
        }
    })
}
func getFbId(){
    if(AccessToken.current != nil){
        let req = GraphRequest(graphPath: "me", parameters: ["fields": "email,first_name,last_name,gender,picture"], accessToken: AccessToken.current, httpMethod: GraphRequestHTTPMethod(rawValue: "GET")!)
        req.start({ (connection, result) in
            switch result {
            case .failed(let error):
                print(error)

            case .success(let graphResponse):
                if let responseDictionary = graphResponse.dictionaryValue {
                    print(responseDictionary)
                    let firstNameFB = responseDictionary["first_name"] as? String
                    let lastNameFB = responseDictionary["last_name"] as? String
                    let socialIdFB = responseDictionary["id"] as? String
                    let genderFB = responseDictionary["gender"] as? String
                    let pictureUrlFB = responseDictionary["picture"] as? [String:Any]
                    let photoData = pictureUrlFB!["data"] as? [String:Any]
                    let photoUrl = photoData!["url"] as? String
                    print(firstNameFB, lastNameFB, socialIdFB, genderFB, photoUrl)
                }
            }
        })
    }
}

Thanks!!!

Upvotes: 0

Aldo Lazuardi
Aldo Lazuardi

Reputation: 1948

If you still got the problem, try this

    let loginManager = LoginManager()

    loginManager.logIn([ .publicProfile, .email, .userFriends ], viewController: self) { loginResult in
        switch loginResult {
        case .failed(let error):
            print(error)
        case .cancelled:
            print("User cancelled login.")

        case .success(let grantedPermissions, let declinedPermissions, let accessToken):
            print("Logged in!")

            let req = GraphRequest(graphPath: "me", parameters: ["fields":"email,first_name,last_name,gender,picture"], accessToken: accessToken, httpMethod: GraphRequestHTTPMethod(rawValue: "GET")!)
        req.start({ (connection, result) in
            switch result {
            case .failed(let error):
                print(error)

            case .success(let graphResponse):
                if let responseDictionary = graphResponse.dictionaryValue {
                    print(responseDictionary)
                    let firstNameFB = responseDictionary["first_name"] as! String
                    let lastNameFB = responseDictionary["last_name"] as! String
                    let socialIdFB = responseDictionary["id"] as! String
                    let genderFB = responseDictionary["gender"] as! String
                    let pictureUrlFB = responseDictionary["picture"] as! [String:Any]
                    let photoData = pictureUrlFB["data"] as! [String:Any]
                    let photoUrl = photoData["url"] as! String
                    print(firstNameFB, lastNameFB, socialIdFB, genderFB, photoUrl)
                }
            }
        })

        }

    }

https://github.com/facebook/facebook-sdk-swift/issues/65

Upvotes: 4

Geoffrey
Geoffrey

Reputation: 155

let parameters = ["fields":"name,gender,birthday,first_name,last_name,email"]
                let graphRequest = FBSDKGraphRequest(graphPath:"me", parameters:parameters)

                _ = graphRequest?.start { [weak self] connection, result, error in
                    // If something went wrong, we're logged out
                    if (error != nil)
                    {
                        print("graphrequest error :\(error?.localizedDescription)")
                        return
                    }

                    // Transform to dictionary first
                    if let result = result as? [String: Any]
                    {
                        guard let firstname = result["first_name"] as? String else {

                            return
                        }

                        guard let lastname = result["last_name"] as? String else {

                            return
                        }

                        guard let gender = result["gender"] as? String else {

                            return
                        }

                        guard let email = result["email"] as? String else {

                            return
                        }

                        guard let birthday = result["birthday"] as? String else {

                            return
                        }

(...)
                    }
                } // End of graph request

Upvotes: 1

Related Questions