Facebook login and App Invites for iOS in Swift - ios

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?

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

Login and Logout with Facebook account

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

Facebook SDK with iOS swift not open in UIWebView [duplicate]

This question already has answers here:
How to integrate Facebook without redirect Safari browser in iOS app with latest FBSDK
(6 answers)
Closed 6 years ago.
I am using Xcode 8.2.1 and FBSDK 4.19.0
I want to open login in with Facebook in a web view instead of Safari.
This is my ViewController:
`import UIKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet var loginButton: FBSDKLoginButton!
var result:NSDictionary=[:]
override func viewDidLoad() {
super.viewDidLoad()
loginButton.delegate = self
if (FBSDKAccessToken.current()) != nil{
fetchProfile()
}
}
func fetchProfile(){
let parameters = ["fields": "name, gender, email, picture.type(large)"]
FBSDKGraphRequest(graphPath: "me", parameters: parameters).start(completionHandler: { (connection, result, error) -> Void in
if(error == nil)
{
self.result = result as! NSDictionary
print(self.result)
}
else
{
print("error \(error)")
}
})
}
func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
print("completed login")
}
func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
}
func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool {
return true
}
}
`
Set the loginBehaviour to .web for FBSDKLoginManager object.
let loginManager = FBSDKLoginManager()
loginManager.loginBehaviour = .web
Since you are using FBSDKLoginButton, in viewDidLoad method, write
loginButton.loginBehaviour = .web

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