如何为新的swift 3撰写Facebook Graph Request?

时间:2016-09-27 04:58:32

标签: swift facebook facebook-graph-api swift3

我正在尝试将新FacebookSdk用于Swift3,但我无法弄清楚如何完成简单的Graph请求。我绝对错了。这就是我在下面的内容。谁有人想出来了?

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

3 个答案:

答案 0 :(得分:4)

如果您仍然遇到问题,请尝试此操作

    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

答案 1 :(得分:1)

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

答案 2 :(得分:0)

> Swift 4的更新:

Facebook SDK版本: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)
                }
            }
        })
    }
}

谢谢!