Im a swift beginner and have already implemented FB login for IOS. I was wondering how to do it with Fast-App-Switching and staying on the App without moving to Facebook login form.
Heres my code for the ViewController.swift handling FB Login:
import UIKit
import Foundation
class FacebookLoginViewController : UIViewController, FBSDKLoginButtonDelegate {
let loginButton: FBSDKLoginButton = {
let button = FBSDKLoginButton()
button.readPermissions = ["public_profile","email","user_friends"]
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(loginButton)
loginButton.center = view.center
loginButton.delegate = self
if let token = FBSDKAccessToken.currentAccessToken() {
fetchProfile()
}
}
func fetchProfile() {
print("User Profile fetched")
redirectToHome()
}
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
print("User has successfully logged on.")
redirectToHome()
}
func redirectToHome() {
let storyboard:UIStoryboard = UIStoryboard(name:"Main", bundle: nil)
let homeFeed: UIViewController = storyboard.instantiateViewControllerWithIdentifier("homeFeed") as UIViewController
self.presentViewController(homeFeed, animated: true, completion: nil)
}
func loginButtonWillLogin(loginButton: FBSDKLoginButton!) -> Bool {
return true
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
print("User has logged out")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
As far as I knew and since I saw your question did further research, it is still not possible to skip the second screen. By second screen I mean a webpage where you must tap "log in" and it provides details about how the app will interact with Facebook. Even the app for this website takes you there when logging in with Facebook. If it this changes or I am mistaken I will update this post. Since I just joined the site I cannot post pictures yet:) but I hope we are talking about the same thing.
Related
Hellos developers,
who anyone can help me with one issue , I try to make a Facebook login and after that I want to go to another view.
But I can't make that happens, could some one can help me with that?
I put my code below:
import UIKit
import FBSDKLoginKit
import FBSDKCoreKit
class ViewController: UIViewController , LoginButtonDelegate{
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?,
error: Error?) {
loginButton.permissions = ["public_profile","email"]
if error != nil {
print("Something is Wrong... \(String(describing: error))")
return
}
print("Succesful loged in !")
}
func loginButtonDidLogOut(_ loginButton: FBLoginButton) {
loginButton.titleLabel?.text = "Adios"
print("GoodBye ")
}
override func viewDidLoad() {
super.viewDidLoad()
let loginButton = FBLoginButton()
loginButton.center = view.center
view.addSubview(loginButton)
loginButton.permissions = ["public_profile", "email"]
loginButton.addTarget(self, action: #selector(getUserFBInfo), for: .touchUpOutside)
}
#objc func getUserFBInfo(){
print("se logro ")
let token = AccessToken.current
if token == AccessToken.current {
performSegue(withIdentifier: "secondActivity", sender: self)
}else if token!.isExpired{
print("no sucede nada")
}
}
}
If you want the LoginButtonDelegate to call your delegate function (e.g. loginbutton:didCompleteWithResult:error:), remember to assign the delegate to the FBLoginButton.
In the above code, since the delegate is the UIViewController itself (not a must), you will need to add loginButton.delegate = self
I am trying to perform a FacebookLogin using Firebase and the Facebook Login button, but I keep getting this
error:Facebook login was cancelled.
2016-04-01 19:08:15.721
biblos[778:408049] Warning: Attempt to present
on
whose view is not in the
window hierarchy!
User logged out...
Facebook login was cancelled.
2016-04-01 19:08:53.675 biblos[778:408049] Warning: Attempt to present
on
whose view is not in the
window hierarchy!
My ViewController code is as follows:
import UIKit
import Firebase
import FBSDKCoreKit
import FBSDKLoginKit
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var loginButton = FBSDKLoginButton()
loginButton.readPermissions = ["public_profile", "email", "user_friends"]
loginButton.center = self.view.center
loginButton.delegate = self
self.view.addSubview(loginButton)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Facebook Login
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{
let ref = Firebase(url: "https://biblos-thebookapp.firebaseio.com")
let facebookLogin = FBSDKLoginManager()
facebookLogin.logInWithReadPermissions(["email"], handler: {
(facebookResult, facebookError) -> Void in
if facebookError != nil {
print("Facebook login failed. Error \(facebookError)")
} else if facebookResult.isCancelled {
print("Facebook login was cancelled.")
} else {
let accessToken = FBSDKAccessToken.currentAccessToken().tokenString
ref.authWithOAuthProvider("facebook", token: accessToken,
withCompletionBlock: { error, authData in
if error != nil {
print("Login failed. \(error)")
} else {
print("Logged in! \(authData)")
}
})
}
})
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
print("User logged out...")
}
}
This method is deprecated. Try to use logInWithReadPermissions:fromViewController:handler: instead and pass your UIViewController or nil (topmost will be used).
https://developers.facebook.com/docs/reference/ios/current/class/FBSDKLoginManager/
I followed the tutorial here to integrate Facebook login on my application. I can login successfully with that button, but it doesn't call my method didCompleteWithResult upon login to fetch user details. This is my code.
import UIKit
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
#IBOutlet weak var loginBtn: FBSDKLoginButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func configureFacebook()
{
loginBtn.readPermissions = ["public_profile", "email", "user_friends"];
loginBtn.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
let strFirstName: String = (result.objectForKey("first_name") as? String)!
let strLastName: String = (result.objectForKey("last_name") as? String)!
let strPictureURL: String = (result.objectForKey("picture")?.objectForKey("data")?.objectForKey("url") as? String)!
print("Welcome, \(strFirstName) \(strLastName)")
//self.profilePic.image = UIImage(data: NSData(contentsOfURL: NSURL(string: strPictureURL)!)!)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
}
}
Option-1
I dont know where you add this method in here I submit answer in dynamically , customize your self..
override func viewDidLoad() {
super.viewDidLoad()
configureFacebook() // if you want here add here or else if you want to load the facebook details in Button action add there
// Do any additional setup after loading the view.
}
func configureFacebook()
{
loginBtn.readPermissions = ["public_profile", "email", "user_friends"];
loginBtn.delegate = self
}
option-2
if you add the delegate in directly in your viewcontroller do like for example
here's the code
override func viewDidLoad()
{
if (FBSDKAccessToken.currentAccessToken() == nil)
{
print("Not logged in..")
}
else
{
let loginView : FBSDKLoginButton = FBSDKLoginButton()
self.view.addSubview(loginView)
loginView.center = self.view.center
loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self //shows error:view controller does not conform to protocol 'FBSDKLoginButtonDelegate'
}
super.viewDidLoad()
}
And the loginButton method
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!)
{
if error == nil
{
print("Login complete.")
self.performSegueWithIdentifier("showNew", sender: self)
}
else
{
print(error.localizedDescription)
}
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!)
{
print("User logged out...")
}
The view controller is frontpageViewConroller,I have logged into facebook registered with the AppId downloaded the iOS SDK and imported them,unable to solve this help me out
thanks in advance!
Have you setting the delegate on you viewController like following code:
class ViewController: UIViewController,FBSDKLoginButtonDelegate {
Please check the following full tutorial login with Facebook for swift
Tutorial: How To Use Login in Facebook SDK 4.1.x for Swift
My name is Nicolás and I am learning how to develop apps for iOS using swift. I need an advice on how to save the user information I retrieve from Facebook Login in order to use it from any view (I was able to use fb login thanks to this tutorial). I tried passing this information through segues but I couldn't achieve this (I recibe this error: Use of unresolved identifier 'userName'). I was thinking maybe something like creating a "global variable" (If they exist in Swift) would be a better practice.
Here is the code of my view controller:
import UIKit
class ViewController: UIViewController, FBLoginViewDelegate {
#IBOutlet var fbLoginView : FBLoginView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.fbLoginView.delegate = self
self.fbLoginView.readPermissions = ["public_profile", "email", "user_friends"]
}
// FACEBOOK DELEGATE METHODS
func loginViewShowingLoggedInUser(loginView : FBLoginView!) {
println("User Logged In")
println("This is where you perform a segue.")
self.performSegueWithIdentifier("gotoview2", sender: self)
}
func loginViewFetchedUserInfo(loginView : FBLoginView!, user: FBGraphUser){
var userName = user.name
}
func loginViewShowingLoggedOutUser(loginView : FBLoginView!) {
println("User Logged Out")
}
func loginView(loginView : FBLoginView!, handleError:NSError) {
println("Error: \(handleError.localizedDescription)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "gotoView2") {
let viewController:SecondViewController = segue!.destinationViewController as SecondViewController
viewController.name = userName // !! HERE IS WHERE I RECIBE THE ERROR !!
}
}
}
Thanks you all very much for your help. I am new to this world and the fact that Swift is so new doesn't helps.
Greetings,
Nico