在swift4中的Facebook集成中获取用户详细信息

时间:2019-04-08 09:30:22

标签: ios swift facebook-graph-api

我正在尝试在集成FBSDK之后获取用户详细信息。但是不幸的是,我收到诸如“使用未解决的标识符'FacebookCore'的使用”之类的错误。如果有人帮助我,那就太好了。谢谢!

//Imported SDK
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit




 func fetchUserProfile()
    {

        let AccessToken = FBSDKAccessToken.current()
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, email, name, picture.width(480).height(480)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: FacebookCore.GraphAPIVersion.defaultVersion))

        request.start({ (response, requestResult) in
        switch requestResult{
        case .success(let response):
        print(response.dictionaryValue)
        case .failed(let error):
        print(error.localizedDescription)
        }
        })
    }

3 个答案:

答案 0 :(得分:0)

您可以通过这种方式获取数据。但是您需要使用pod或手动安装新的最新库

import FBSDKLoginKit
func signInWithFB(_ forVC:UIViewController , sucess:@escaping (_ data:NSMutableDictionary) -> (Void) , falure:@escaping (_ error:NSError? , _ cancle:Bool?) -> (Void))
    {
        let obj_facebook = FBSDKLoginManager()
        obj_facebook.loginBehavior = .native
        obj_facebook.logOut()
//        "user_birthday","user_gender"
        obj_facebook.logIn(withReadPermissions: ["public_profile","email"], from: forVC) { (result:FBSDKLoginManagerLoginResult?, error:Error?) -> Void in
            if ((error) != nil)
            {
                falure(error as NSError?, false)
            }
            else if ((result?.isCancelled) == true)
            {
                falure(nil, true)
            }
            else
            {
                let dicLoginData = NSMutableDictionary()
//                name,email,first_name,last_name,birthday
                let request = FBSDKGraphRequest(graphPath: "/me?fields=name,email,first_name,last_name", parameters: nil)
                let _ =
                request?.start(completionHandler: { (Connection:FBSDKGraphRequestConnection?, result:Any!, error:Error?) -> Void in

                    if error == nil
                    {
                        guard let results = result as? [String: Any] else {
                            falure(nil, false)
                            return
                        }
                        sucess(result)
                    }
                    else
                    {
                        falure(error as NSError?, false)
                    }

                })

            }
        }
    }

答案 1 :(得分:0)

import FBSDKCoreKit
import FBSDKLoginKit


var facebookInfoDict = [String:AnyObject]()
var profileURL = ""
var facebookName = ""
var socialDetailDict = [String:AnyObject]()


@IBAction func loginWithFacebookAction(_ sender: UIButton) {


    let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
    fbLoginManager.logOut()
    fbLoginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends"], from: self) { (result, error) -> Void in
        if (error == nil){
            let fbloginresult : FBSDKLoginManagerLoginResult = result!
            // if user cancel the login
            if (result?.isCancelled)!{
                return
            }
            if(fbloginresult.grantedPermissions.contains("email")) {

                if Reachability.isConnectedToNetwork() {
                    self.getFBUserData()
                } else {

                }
            }
        }
    }
}

//function is fetching the  facebook user data
func getFBUserData(){
    if((FBSDKAccessToken.current()) != nil){
        FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
            if (error == nil){
                self.facebookInfoDict = result as! [String : AnyObject]
                print(self.facebookInfoDict)
                if let profileData = self.facebookInfoDict["picture"]!["data"] as? Dictionary<String, AnyObject> {
                    self.socialDetailDict = self.facebookInfoDict
                    self.profileURL = profileData["url"] as! String
                    self.facebookName = self.facebookInfoDict["name"] as! String

                    UserDefaults.standard.synchronize()
                }

            }
        })
    }
}

答案 2 :(得分:0)

您可以尝试集成“ FacebookCore”和“ FacebookLogin”

pod 'FacebookLogin'
pod 'FacebookShare'

安装Pod后,请尝试以下代码,它用于Swift 4

import FacebookLogin
import FacebookCore

@IBAction func btnFacebookLoginTapped(_ sender: Any) {

    let loginManager = LoginManager()
    loginManager.logIn(readPermissions: [.publicProfile, .email], viewController: self) { (result) in

        switch result {
        case .success(grantedPermissions: _, declinedPermissions: _, token: _):
            print("Succesfully logged in into Facebook.")
            self.fetchFacebookUser()

        case .failed( let error ):
            print(error)
            self.showAlertError(TL("warning_facebook_connect_failed"))

        case .cancelled: break

        }
    }
}

fileprivate func fetchFacebookUser() {

    let graphRequestConnection = GraphRequestConnection()
    let graphRequest = GraphRequest(graphPath: "me", parameters: ["fields": "id, email, name, picture.type(large)"], accessToken: AccessToken.current, httpMethod: .GET, apiVersion: .defaultVersion)
    graphRequestConnection.add(graphRequest, completion: { (httpResponse, result) in
        switch result {
        case .success(response: let response):
            print(responseDict)

        case .failed( _):
        }
    })
    graphRequestConnection.start()
}