How to Remove the Logout Button and store the session permanently FBSDK IOS using Swift

*爱你&永不变心* 提交于 2019-12-24 02:59:09

问题


I am creating an app in which user can Sign in using Facebook. I am fetching user info like profile picture Username etc. Now when i tap on Login with facebook button FB ask for permission i am loged in. but then there is Logout Button displaying at the same place as LoginWithFacebook button was. I want to Remove the logout button because i do not want the user to log out. I want to store the session and use it all the way long until app is unintsalled because I do not want the user to login each time when he opens the app. This is my code so far

class ViewController: UIViewController, FBSDKLoginButtonDelegate {
@IBOutlet weak var btnFacebook: FBSDKLoginButton!
@IBOutlet weak var ivUserProfileImage: UIImageView!
@IBOutlet weak var lblName: UILabel!
var strFirstName: String!
var strLastName: String!
var strPictureURL: String!

override func viewDidLoad() {
    super.viewDidLoad()
    configureFacebook()
}

func configureFacebook()
{
    btnFacebook.readPermissions = ["public_profile", "email", "user_friends"];
    btnFacebook.delegate =  self
}

func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{
    FBSDKGraphRequest.init(graphPath: "me", parameters: ["fields":"first_name, last_name, picture.type(large)"]).startWithCompletionHandler { (connection, result, error) -> Void in
        //fetching first and last name
        self.strFirstName = (result.objectForKey("first_name") as? String)!
        self.strLastName = (result.objectForKey("last_name") as? String)!
        self.strPictureURL = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String)!
        // contactinating first and last name
        self.lblName.text = "Welcome, \(self.strFirstName) \(self.strLastName)"
        // assinging image
        self.ivUserProfileImage.image = UIImage(data: NSData(contentsOfURL: NSURL(string: self.strPictureURL)!)!)
        }
}

func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
    let loginManager: FBSDKLoginManager = FBSDKLoginManager()
    //for logging out from facebook
    loginManager.logOut()
}

回答1:


Add fb login button variable manually to your view controller

let fbLoginBtn = FBSDKLoginButton()

In your viewDidLoad

view.addSubView(fbLoginBtn)

Handle hidden state of login btn by check FBSDKAccessToken.currentAccessToken() has value or not

And you can logout programmatically by FBSDKLoginManager().logOut()




回答2:


You can hide logout button after login via facebook by using below code like,

 if(FBSDKAccessToken.currentAccessToken() != nil)
 {
       self.btnFacebook.hidden = true
 }
 else
 {
       self.btnFacebook.hidden = false
 }

NOTE: You need to check this after every login and logout in your code so that you can easily maintain that button log.

For Session, Write this in viewDidLoad of LoginController to get user info,

    self.btnFacebook.delegate = self
    self.btnFacebook.readPermissions = ["public_profile","email","user_friends"]

    FBSDKProfile.enableUpdatesOnAccessTokenChange(true)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "getUserProfile:", name: FBSDKProfileDidChangeNotification, object: nil)

    if(FBSDKAccessToken.currentAccessToken() != nil)
    {
        let accessToken = FBSDKAccessToken.currentAccessToken()
        if(accessToken != nil)
        {

            let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
            req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
                if(error == nil)
                {
                    let userInfo = result as AnyObject
                    if let _ = userInfo.valueForKey("email") as? NSString
                    {
                        // Extract user info here
                        let userDic : NSDictionary = NSDictionary(dictionary: userInfo as! [NSObject : AnyObject])
                        print(userDic)
                    }
                    else
                    {
                       // Logout if you want or display error message
                       // let loginManager = FBSDKLoginManager()
                       // loginManager.logOut()
                    }
                }

            })
        }
    }

Call this observer method,

func getUserProfile(notification : NSNotification)
{
    let accessToken = FBSDKAccessToken.currentAccessToken()
    if(accessToken != nil)
    {

        let req = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"email,name"], tokenString: accessToken.tokenString, version: nil, HTTPMethod: "GET")
        req.startWithCompletionHandler({ (connection, result, error : NSError!) -> Void in
            if(error == nil)
            {
                let userInfo = result as AnyObject
                if let _ = userInfo.valueForKey("email") as? NSString
                {
                    let userDic : NSDictionary = NSDictionary(dictionary: userInfo as! [NSObject : AnyObject])
                    print(userDic)
                }
                else
                {
                    // logout or error message 
                    //let loginManager = FBSDKLoginManager()
                    //loginManager.logOut()
                }
            }
        })
    }
}

Hope this will help you.



来源:https://stackoverflow.com/questions/37341398/how-to-remove-the-logout-button-and-store-the-session-permanently-fbsdk-ios-usin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!