我正在尝试使用Facebook SDK for iOS使用自定义Facebook登录来获取用户信息。我成功登录用户,但我不知道如何访问用户信息。 这是我的登录功能:
func facebookLogin() {
if (FBSession.activeSession().state == FBSessionState.Open || FBSession.activeSession().state == FBSessionState.OpenTokenExtended)
{
// Close the session and remove the access token from the cache
// The session state handler (in the app delegate) will be called automatically
FBSession.activeSession().closeAndClearTokenInformation()
}
else
{
// Open a session showing the user the login UI
// You must ALWAYS ask for public_profile permissions when opening a session
FBSession.openActiveSessionWithReadPermissions(["public_profile", "email"], allowLoginUI: true, completionHandler: {
(session:FBSession!, state:FBSessionState, error:NSError!) in
self.sessionStateChanged(session, state: state, error: error)
})
}
}
然后当会话打开时,调用函数sessionStateChanged:
func sessionStateChanged(session:FBSession, state:FBSessionState, error:NSError?){
if ((error) != nil){
NSLog("Error")
FBSession.activeSession().closeAndClearTokenInformation()
}
else{
if (state == FBSessionState.Open){
//I would like to get the user token or FBGraphUser here but i don't know how
}
}
if (state == FBSessionState.Closed || state == FBSessionState.ClosedLoginFailed){
NSLog("Session Clossed")
}
if (FBErrorUtility.shouldNotifyUserForError(error) == true){
NSLog("Something went wrong")
}
else{
if (FBErrorUtility.errorCategoryForError(error) == FBErrorCategory.UserCancelled){
NSLog("User cancelled login")
}
else if (FBErrorUtility.errorCategoryForError(error) == FBErrorCategory.AuthenticationReopenSession){
NSLog("Current session is no valid")
}
}
}
答案 0 :(得分:1)
今天遇到完全相同的问题!我不确定这是否是理想的做事方式,但这是我的同事向我展示的解决方法:
FBSession.openActiveSessionWithReadPermissions(["public_profile"], allowLoginUI: false) { session, state, error in
let request = FBRequest(session: FBSession.activeSession(), graphPath: "/me")
request.startWithCompletionHandler({ (connection, result, error) -> Void in
println(result)
let birthday = result.valueForKey("birthday") as String
println("\(birthday)")
})
self.fbSessionStateChanged(session, state: state, error: error)
}
请原谅丑陋的代码,我还在尝试使用Swift。希望它有所帮助!
答案 1 :(得分:1)
您可以使用:
将FBLoginViewDelegate添加到班级
声明此
@IBOutlet var fbLoginView : FBLoginView!
将此var(fbLoginView)与故事板中的新视图相关联。这个新视图可以隐藏,因此它不会产生任何影响,但可以帮助您跟踪信息
在viewDidLoad
中override func viewDidLoad() {
super.viewDidLoad()
//facebook login
self.fbLoginView.delegate = self
self.fbLoginView.readPermissions = ["public_profile", "email"]
}
并添加此功能
func loginViewFetchedUserInfo(LoginView : FBLoginView!, user: FBGraphUser){
println("User name: \(user.name)")
//THE USER WAS LOGGED
}
当用户通过facebook验证时,使用FBLoginViewDelegate自动返回loginViewFetchedUserInfo方法,您可以使用“user”变量获取信息