2

我想将用户名字段中用户的用户名提取到解析中。

我正在使用loginWithFacebook(withcompletionHandler)fetchUserInforFromFacebook(withcompletionHandler)获取用户信息,但我有一个问题:这些方法创建一个自己的对象并存储在解析用户名字段中,但我想获取用户用户名。

func loginWithFacebook(withcompletionHandler: (success:Bool) ->()){
    var permissions : Array = [ "user_location","public_profile"]
    PFFacebookUtils.logInInBackgroundWithReadPermissions(permissions, {
        (user: PFUser?, error: NSError?) -> Void in
        if let user = user {
            if user.isNew {

                self.fetchUserInforFromFacebook(withcompletionHandler)

                println("User SIGNED UP and logged in through Facebook!")
                }
            withcompletionHandler(success: true)
            println("User logged in through Facebook!")

        } else {
            println("Uh oh. The user cancelled the FACEBOOK LOGIN.")
            self.showErrorMessage(error!)
            withcompletionHandler(success: false)
        }
    })
}
func fetchUserInforFromFacebook(withcompletionHandler: (success:Bool) ->()){
    if ((FBSDKAccessToken.currentAccessToken()) != nil){

        var request = FBSDKGraphRequest(graphPath:"me", parameters:nil)
        request.startWithCompletionHandler({connection, result, error in
            if error == nil {

                //FACEBOOK DATA IN DICTIONARY
                var userData = result as NSDictionary
                var currentUser : PFUser = PFUser.currentUser()
                currentUser.setObject(userData.objectForKey("id") as String, forKey: "faceBookID")
                currentUser.setObject( userData.objectForKey("name") as String, forKey: "fullName")
                                currentUser.email = userData.objectForKey("email") as? String
                currentUser.username = userData.objectForKey("email") as? String






                var location = userData.objectForKey("location") as? NSDictionary
                var locName = location?.objectForKey("name") as? String
                if let loc =  locName {
                    var fullNameArr = split(loc) {$0 == ","}
                    var city: String? = fullNameArr.count > 0 ? fullNameArr[0] : nil
                    var contry: String? = fullNameArr.count > 1 ? fullNameArr[1]: nil

                    currentUser.setObject(userData.objectForKey("country"), forKey: "countryName")
                    currentUser.setObject(userData.objectForKey("city"), forKey: "cityName")

                }
                currentUser.saveInBackground()
                withcompletionHandler(success: true)

            }else{
                println("Error")
                self.showErrorMessage(error)
                withcompletionHandler(success: false)
            }
        })


    }

}
4

2 回答 2

1

获取用户名更简单的方法:

首先 ,您需要调用 FBSession 方法来获取用户的基本配置文件信息和 ID。

其次 ,一旦我们得到用户 FB ID,我们可以直接在图形 API 中传递 FB ID:https://graph.facebook.com/?id=1008223822a 并获取以下 json 格式的用户名:-

{
   "id": "1008223822",
   "first_name": "Dj\u00e9",
   "gender": "male",
   "last_name": "Destolicci",
   "link": "https://www.facebook.com/dje.destolicci",
   "locale": "fr_FR",
   "name": "Dj\u00e9 Destolicci",
   "username": "dje.destolicci"
}

这是代码: -


//first do simple login and authenticate user to get basic profile info and FB ID
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email", "user_friends"] , allowLoginUI: true, completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) -> Void in
            if (error==nil)
            {
                FBRequest.requestForMe().startWithCompletionHandler({ (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in

                    if (error==nil)
                    {

                        var bUserFacebookDict = result as! NSDictionary

                        let FB_USER_ID = bUserFacebookDict["id"]! as! String

                        // now call FB graph API to to Get username of the user.
                        var graphProfileURL = NSURL(string: "https://graph.facebook.com/?id=\(FB_USER_ID)")


                        var request1: NSURLRequest = NSURLRequest(URL: graphProfileURL!)
                        var response: AutoreleasingUnsafeMutablePointer<NSURLResponse?
                        >=nil
                        var error: NSErrorPointer = nil
                        var dataVal: NSData =  NSURLConnection.sendSynchronousRequest(request1, returningResponse: response, error:nil)!
                        var err: NSError
                        println(response)
                        var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(dataVal, options: NSJSONReadingOptions.MutableContainers, error: nil) as! NSDictionary
                        println("Synchronous\(jsonResult)")


                        let FB_USER_NAME = jsonResult["username"]! as! String //finally you will get username


                    }
                    else
                    {
                        //Utility.showErrorAlert(error.description)
                    }
                })
            }
        })
于 2015-05-15T06:31:22.203 回答
1
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email", "user_friends"] , allowLoginUI: true, completionHandler: { (session:FBSession!, state:FBSessionState, error:NSError!) -> Void in
                if (error==nil)
                {
                    FBRequest.requestForMe().startWithCompletionHandler({ (connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in

                        if (error==nil)
                        {
                            // get All Facebook data from user
                            //http://graph.facebook.com/67563683055/picture?type=square
                            //NSLog("%@",result as! NSDictionary)
                            var bUserFacebookDict = result as! NSDictionary

                            bstrFirstName = bUserFacebookDict.objectForKey("first_name") as! String
                            bstrLastName = bUserFacebookDict.objectForKey("last_name") as! String
                            bstrUserName = bUserFacebookDict.objectForKey("name") as! String

                        }
                        else
                        {
                            //Utility.showErrorAlert(error.description)
                        }
                    })
                }
            })
于 2015-05-15T06:48:30.900 回答