2

ユーザー名フィールドのユーザーのユーザー名を解析にフェッチしたい。

loginWithFacebook(withcompletionHandler)ユーザー情報を取得するためにandを使用し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.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 に答える
1

ユーザー名を取得するためのはるかに簡単な方法:

まず 、FBSession メソッドを呼び出して、ユーザーの基本的なプロファイル情報と ID を取得する必要があります。

次に 、ユーザーの FB ID を取得したら、グラフ API で FB ID を直接渡すことができます。https://graph.facebook.com/?id=1008223822次の 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 に答える