Login and Logout with Facebook account - ios

I want to add login with Facebook account to my IOS app. I tried installing FacebookCore pod and FacebookLogin pod. My login action was successful but when I try to logout then login again, browser used the previous logged in account. Here is my code for login and logout action:
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = LoginButton(readPermissions: [ .publicProfile ])
loginButton.center = view.center
//adding it to view
view.addSubview(loginButton)
loginButton.delegate = self
}
func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
print("logged in")
self.loginButtonClicked()
}
func loginButtonDidLogOut(_ loginButton: LoginButton) {
print("logged out")
AccessToken.current = nil
UserProfile.current = nil
FBSDKLoginManager().logOut()
}
//when login button clicked
func loginButtonClicked() {
let loginManager = LoginManager()
loginManager.loginBehavior = .web
loginManager.logIn(readPermissions: [.publicProfile], viewController: self, completion: {loginResult in
switch loginResult {
case .failed(let error):
print("loginnnnnn errrooorrr",error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
self.getFBUserData()
}
})
}
//function is fetching the user data
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as! [String : AnyObject]
self.isLogin = true
print(result!)
print(self.dict)
}
})
}
}
How to login with another account?

I had similar issue, I was receiving
you previously logged in to [app name] with Facebook. Would you like
to continue?
every time I wanted to log in into my app even after logout.
I solved it by using of Facebook native app (ver. 177).
You can 'log out' from your app here:
Menu Tab -> Settings -> 'Apps and Websites' -> 'Logged in with Facebook' -> Active -> select app -> tap Remove

Related

How do I implement facebook login?

I'm trying to implement facebook login on IOS using the new Facebook SDK. I'm getting stuck because I'm using my own custom facebook login button, where the SDK requires you to use its own login button. Can someone please help? I need to implement the part where someone click on the custom login button and authenticates using facebook after granting permission. Thanks!
I looked at the Documentation and it only provides support for Objective C and not swift
Here's what I had before the SDK update that no longer works
let loginManager = LoginManager()
loginManager.logIn(permissions: [ ".publicProfile, .email" ], viewController: self) { loginResult in
switch loginResult {
case .failed:
self.showMessage("Error logging you in.", "Could not log you in. Please try again.", .error)
case .cancelled:
self.showMessage("User canceled login.", "User cancelled login. Please try again.", .error)
case .success:
self.setFBUserData()
}
}
You can do this tricks. Initially create a facebookLoginButton but this will be hidden.
let facebookLoginButton = FBLoginButton(frame: .zero, permissions: [.publicProfile, .email])
facebookLoginButton.delegate = self
facebookLoginButton.isHidden = true
and in your custom button action you just needed to process the action
#IBAction func registerWithFacebook(_ sender: UIButton) {
facebookLoginButton.sendActions(for: .touchUpInside)
}
Hope you can understand.
About this trick you can check more: https://medium.com/#emmavagradyan/handle-facebook-login-with-custom-button-in-ios-3f1c99faeb55
Configuration about FacebookLogin: https://itnext.io/swift-facebook-ios-login-sdk-dada412d8341
For the Custom Design I did this way. First create a customView For the Custom Button and add Tap Gesture to that View.
create outlet of your view
#IBOutlet weak var fbLoginContainerView: UIView!
then add tap gesture to that view
let fbContainerTapGesture = UITapGestureRecognizer(target: self, action: #selector(fbLoginVIewAction(_:)))
fbLoginContainerView.addGestureRecognizer(fbContainerTapGesture)
in action getFBUserData
#objc func fbLoginVIewAction(_ sender: UITapGestureRecognizer) {
let loginManager = LoginManager()
loginManager.logIn(permissions: ["public_profile", "email"] , viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
self.getFBUserData()
}
}
}
fileprivate func getFBUserData(){
if((AccessToken.current) != nil){
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as? [String : AnyObject]
print(result!)
print(self.dict)
self.showProgress(on: self.view)
guard let Username = self.dict["name"]! as? String else { return }
guard let UserId = self.dict["id"]! as? String else { return }
guard let Useremail = self.dict["email"]! as? String else { return }
let params = ["provider_user_id": UserId , "name": Username, "email": Useremail ,"provider": "FacebookProvider"] as! [String: AnyObject]
//Do your sign in network call here with parameter
}
}
See the Button ScreenShot

Facebook login and App Invites for iOS in Swift

I am stuck after coding the Facebook login.....!
After the login procedure I just end up with a logout button.
I would like to make use of the App Invites for iOS but I cant figure out how to integrate it...
The documentations on "Facebook.developer" is hard to understand.
This is my code so far in the view controller:
import UIKit
import FacebookLogin
import FBSDKLoginKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
var dict : [String : AnyObject]!
override func viewDidLoad() {
super.viewDidLoad()
//creating button
let loginButton = LoginButton(readPermissions: [ .publicProfile, .userFriends, .email ])
loginButton.center = view.center
//adding it to view
view.addSubview(loginButton)
//if the user is already logged in
if let accessToken = FBSDKAccessToken.current(){
getFBUserData()
}
}
//when login button clicked
#objc func loginButtonClicked() {
let loginManager = LoginManager()
loginManager.logIn([ .publicProfile, .userFriends, .email ], viewController: self) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
case .cancelled:
print("User cancelled login.")
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
self.getFBUserData()
}
}
}
//function is fetching the user data
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, picture.type(large), email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as! [String : AnyObject]
print(result!)
print(self.dict)
}
})
}
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
/*
Check for successful login and act accordingly.
Perform your segue to another UIViewController here.
*/
let viewController = self.storyboard?.instantiateInitialViewController("StoryBoardID") as? UITableViewController
self.presentViewController(viewController, animated: true, completion: nil)
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
// Actions for when the user logged out goes here
}
}
Any help?

"Not Now" button handling in **Facebook-SDK**

In Facebook-Login when user enters "Username & Password" then on safari Facebook-SDK showing below screen.
If the user clicks on Not Now rather that on Continue as User. Facebook-SDK returns always Success
Is this Facebook-SDK bug or I am missing something.
I am adding below code:
func fbLoginWithViewController(viewController :UIViewController, completion : #escaping (_ loginResult: AnyObject, _ error: NSError?) -> Void) {
let loginManager = LoginManager()
loginManager.loginBehavior = .systemAccount
loginManager.logIn([ .publicProfile,.userFriends,.email ], viewController: viewController) { loginResult in
switch loginResult {
case .failed(let error):
print(error)
// show error method
self.isCancelled = false
completion(loginResult as AnyObject,error as NSError?)
case .cancelled:
print("User cancelled login.")
// show cancelled error
self.isCancelled = true
completion(loginResult as AnyObject,nil)
case .success(let grantedPermissions, let declinedPermissions, let accessToken):
print("Logged in!")
//add api
self.isCancelled = false
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email, picture.width(180).height(180)"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.fbAccesstoken = FBSDKAccessToken.current().tokenString
completion(result as AnyObject,nil)
}
})
}
}
}
}
Let me know if I am doing wrong!

Facebook SDK and Swift 2.0 - Problems with handling accessToken

my name is Vincent and I need your help !
(My code is not exhaustive)
No problem to login or logout with the Facebook SDK ... BUT
When I start my app, no access token and when i click on the Login button, it prints me an accessToken, then I logout.
How to get the accessToken when the app starts ?
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getUserStatuts()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK -> Facebook Connect
func loginToFacebook() {
if let fbToken = FBSDKAccessToken.currentAccessToken() {
print("Acces token : \(fbToken)")
loginManager.logOut()
print("Logout")
} else {
print("Login")
loginManager.logInWithPublishPermissions(publishPermissions, fromViewController: nil, handler: {
(result:FBSDKLoginManagerLoginResult!, error:NSError!) -> Void in
if error == nil {
self.getUserData()
} else {
print(error.localizedDescription)
}
})
}
}
func getUserData() {
let readPermissions = ["public_profile", "email", "user_friends", "user_birthday"]
let parameters = ["fields": "id, first_name, last_name, name, birthday, picture.type(large)"]
let request = FBSDKGraphRequest(graphPath: "me", parameters: parameters)
request.startWithCompletionHandler({
(connection, result, error) -> Void in
if error == nil {
// display info
}
})
}
In the login function you want to implement the
let fbLogin = FBSDKLoginManager()
fblogin.logout()
the fblogin.logout() must be implemented before fbLogin.logInWithReadPermissions(["email"], fromViewController: self) { (facebookResult, facebookError) in
if facebookError != nil { ` to clear any access tokens from previous login.

Facebook FBSDKLoginManager/logInWithReadPermissions Swift Example not using Parse

Where is the latest Facebook Swift Documentation. I can't get the FB Login Dialog to show up. The call to loginWithReadPermissions never returns?
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController {override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let loginManager = FBSDKLoginManager()
loginManager.logInWithReadPermissions(["basic_info", "email", "user_likes"], fromViewController: self.parentViewController, handler: { (result, error) -> Void in
if error != nil {
print(FBSDKAccessToken.currentAccessToken())
} else if result.isCancelled {
print("Cancelled")
} else {
print("LoggedIn")
}
})
}
You code should work if you exclude "user_likes" from permissions.
From facebook docs:
If your app asks for more than public_profile, email and user_friends, Facebook must review it before you release it. Learn more about the review process and what's required to pass review.
https://developers.facebook.com/docs/facebook-login/permissions/v2.5#reference-user_likes
Another problem may be that you have not set correctly the FacebookSDK in your project. See this tutorial: https://developers.facebook.com/docs/ios/getting-started/
So the answer is to use FBSDKLoginButton with the following
In the class declaration of the viewController
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate
Then show the FBLogin Button with
// Setup the FB Login/Logout Button FB will take care of the
// verbiage based on the current access token
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
// If we have an access token, then let's display some info
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// Display current FB premissions
print (FBSDKAccessToken.currentAccessToken().permissions)
// Since we already logged in we can display the user datea and taggable friend data.
self.showUserData()
self.showFriendData()
}
Show the users info with
func showUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "id, name, gender, first_name, last_name, locale, email"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
let userName : NSString = result.valueForKey("name") as! NSString
print("User Name is: \(userName)")
if let userEmail : NSString = result.valueForKey("email") as? NSString {
print("User Email is: \(userEmail)")
}
}
})
}
And to display the taggable friends
func showFriendData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me/taggable_friends?limit=999", parameters: ["fields" : "name"])
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(error)")
}
else
{
if let friends : NSArray = result.valueForKey("data") as? NSArray{
var i = 1
for obj in friends {
if let name = obj["name"] as? String {
print("\(i) " + name)
i++
}
}
}
}
})
}

Resources