如何在 Swift 中从 Facebook 获取用户名
Posted
技术标签:
【中文标题】如何在 Swift 中从 Facebook 获取用户名【英文标题】:How to get the username from Facebook in Swift 【发布时间】:2015-05-15 06:22:31 【问题描述】:我想将用户名字段中的用户名提取到解析中。
我正在使用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)
)
【问题讨论】:
【参考方案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)
)
)
【讨论】:
OP 要求输入用户名?没有一个答案能满足 OP 的问题 我认为名字键是给你的用户名的。【参考方案2】:获取用户名更简单的方法:
首先 您需要调用 FBSession 方法来获取用户的基本个人资料信息和 ID。
其次 一旦我们得到用户的FB ID,我们就可以直接在graph API中传递FB ID:https://graph.facebook.com/?id=1008223822
a,得到如下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)
)
)
【讨论】:
为什么要在FBRequestConnection startWithGraphPath...
周围增加一个块?
@Vizllx 用户名在 v2.0 中被 Facebook 弃用,但我猜他的意思是全名。 basic_info 也已被弃用并被 public_profile 取代。
用户名存储在解析中,如“xjgh4556hsjsjsjj”,但我想获得正确的用户名,如“Rock”,我们该怎么做?
@UsmanJaved-检查我更新的答案,它将返回您的用户名。
@Vizllx - "use the undeclared type FBSession" 此错误发生在此代码中以上是关于如何在 Swift 中从 Facebook 获取用户名的主要内容,如果未能解决你的问题,请参考以下文章
如何在 ios 中从 facebook 获取朋友的最新状态?
如何在 C# 中从 Facebook SDK 获取当前用户访问令牌?不是应用访问令牌
如何在 iOS 9 fb sdk 4.8 或更高版本中从 facebook 获取好友列表?
如何在统一引擎中从 Facebook API 获取用户名和用户个人资料图片?
如何在 Swift beta 3 中从 UIImagePickerControllerDelegate 获取 UIImage?