简体   繁体   中英

iOS: Check if user is already logged in using Facebook?

I have started working on an iOS app on Xcode using Swift and storyboards. I have a requirement where on click of a button I will show a user's Facebook profile info on the screen (only if user is signed in using Facebook), but if he is not signed in it will automatically go to login screen and on successful login again the profile view will be shown.

How can I do this?

If you're using the Facebook Login SDK, call

FBSDKAccessToken.currentAccessToken()

It will be not nil if the user is logged in.

https://developers.facebook.com/docs/facebook-login/ios/v2.3#token

With latest Facebook SDK, You can check like this :

if FBSDKAccessToken.current() != nil {
    // logged in
}
else {
    // not logged in 
}

They recently changed from FBSDKAccessToken.currentAccessToken() to FBSDKAccessToken.current()

For more convenient and standard code in swift you can use this following code snippet. BTW I am using Swift 2.2 and Xcode 7.3.1.

if let loggedInUsingFBTokenCheck = FBSDKAccessToken.currentAccessToken(){
     //User is already logged-in. Please do your additional code/task.
}else{
    //User is not logged-in. Allow the user for login using FB.
}

If you want to load specific viewController during app launch based on login check you can place this code inside your project's AppDelegate and check inside -

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//Check here for login
}

Thank You.

in sdk for swift 5 use the next portion of code:

import FBSDKCoreKit

if AccessToken.isCurrentAccessTokenActive {
    print("your session is active")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM