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

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

Related

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?

graphRequest.start returns no data

I'm using the Facebook SDK for login with iOS using Swift 3.
This my code. The problem is that no values are returned.
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var email: UITextField!
#IBOutlet weak var password: UITextField!
#IBOutlet weak var uLoginButton: UIButton!
let loginButton: FBSDKLoginButton = {
let button = FBSDKLoginButton()
button.readPermissions = ["email"]
return button;
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(loginButton);
loginButton.center = view.center
loginButton.delegate = self
if (FBSDKAccessToken.current() != nil) {
fetchProfile();
}
self.style()
}
func fetchProfile(){
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "email, name, first_name, last_name, picture.type(large)"])
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) in
if error != nil {
//do something with error
print("No Data returned")
print(result)
} else {
//do something with result
print("Data returned")
print(result)
}
})
connection.start()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func style(){
self.email.layer.cornerRadius = 15;
self.password.layer.cornerRadius = 15;
self.uLoginButton.layer.cornerRadius = 15;
}
}
extension ViewController : FBSDKLoginButtonDelegate{
internal func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
// when the login is correct!
print("Success login!");
fetchProfile()
}
internal func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
FBSDKAppEvents.activateApp()
}
internal func loginButtonWillLogin(_ loginButton: FBSDKLoginButton!) -> Bool {
return true
}
}
In Swift 3, this is how you want to perform Graph Request.
Initialize FBSDKGraphRequest
Initialize FBSDKGraphRequestConnection
Add request to request connection
Start connection.
so,
let graphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields" : "email"])
let connection = FBSDKGraphRequestConnection()
connection.add(graphRequest, completionHandler: { (connection, result, error) in
if error != nil {
//do something with error
} else {
//do something with result
}
})
connection.start()

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.

I'm trying integerate facebook login it shows "view controller does not conform protocol"

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

Parse Facebook Login/Signup Not Working (Swift)

I've been frustratingly trying to implement Parse's Facebook login function into my app using Swift for over a month and can't seem to figure it out. I successfully linked my app to both Facebook and Parse separately, but I can't make a Parse user using Facebook's login. I believe the AppDelegate is setup correctly, so I will only show my LoginViewController and hopefully someone who knows what they're doing can please help me out:
import UIKit
import Parse
import FBSDKCoreKit
import FBSDKLoginKit
protocol LoginViewControllerDelegate {
func onRegister(loginViewController : LoginViewController)
func onFacebookLogin(loginViewController : LoginViewController)
func onLogin(loginViewController : LoginViewController)
}
class LoginViewController: UIViewController, FBSDKLoginButtonDelegate {
//MARK: - Outlets
#IBOutlet weak var lblStatus: UILabel!
//var delegate : LoginViewControllerDelegate?
// Set permissions required from the facebook user account
let permissions = [ "user_about_me", "user_relationships", "user_location", "user_birthday", "public_profile", "user_friends", "user_email", "user_gender"]
//MARK: - Initial Load
override func viewDidLoad() {
super.viewDidLoad()
self.lblStatus.alpha = 0
//Facebook
if (FBSDKAccessToken.currentAccessToken() != nil)
{
// User is already logged in, do work such as go to next view controller.
}
else
{
let loginView : FBSDKLoginButton = FBSDKLoginButton()
// self.view.addSubview(loginView)
// loginView.center = self.view.center
// loginView.readPermissions = ["public_profile", "email", "user_friends"]
loginView.delegate = self
}
// ---------------------------- Check if user is logged in ---------------------
if PFUser.currentUser() != nil {
println("parse: User already logged in")
performSegueWithIdentifier("loggedIn", sender: self)
}
}
//MARK: - Facebook Login Button
func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
if ((error) != nil) {
println(error) // Process error
} else if result.isCancelled { // Handle cancellations
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if result.grantedPermissions.contains("email")
{
// Do work
}
}
returnUserData()
}
#IBAction func facebookLoginDidPress(sender: AnyObject) {
self.lblStatus.alpha = 0
PFFacebookUtils.logInInBackgroundWithReadPermissions(self.permissions, block: {
(user: PFUser?, error: NSError?) -> Void in
if (user == nil) {
if (error == nil) {
println("User cancelled FB login")
self.lblStatus.alpha = 1
}else{
println("FB login error: \(error)")
self.lblStatus.alpha = 1
}
} else if user!.isNew {
println("User signed up and logged in with Facebook! \(user)")
self.requestFacebook()
self.returnUserData()
self.performSegueWithIdentifier("loggedIn", sender: self)
} else {
println("User logged in via Facebook \(user)")
self.performSegueWithIdentifier("loggedIn", sender: self)
}
})
}
func requestFacebook() {
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else if error == nil
{
var userData: NSDictionary = NSDictionary(objectsAndKeys: result)
var facebookID: AnyObject? = userData["id"]
var name: AnyObject? = userData["first_name"]
var gender: AnyObject? = userData["gender"]
var birthday: AnyObject? = userData["birthday"]
var pictureURL = "https://graph.facebook.com/\(facebookID)/picture?type=large&return_ssl_resources=1"
var URLRequest = NSURL(string: pictureURL)
var URLRequestNeeded = NSURLRequest(URL: URLRequest!)
NSURLConnection.sendAsynchronousRequest(URLRequestNeeded, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!, error: NSError!) -> Void in
if error == nil {
var picture = PFFile(data: data)
PFUser.currentUser()!.setObject(picture, forKey: "profilePicture")
PFUser.currentUser()!.saveInBackground()
}
else {
println("Error: \(error.localizedDescription)")
}
})
}
})
}
func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
println("User Logged Out")
}
func returnUserData()
{
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
if let userName : NSString = result.valueForKey("name") as? NSString {
println("User Name is: \(userName)")
} else {println("No username fetched")}
if let userEmail : NSString = result.valueForKey("email") as? NSString {
println("User Email is: \(userEmail)")
} else {println("No email address fetched")}
if let userGender : NSString = result.valueForKey("gender") as? NSString {
println("User Gender is: \(userGender)")
} else {println("No gender fetched") }
}
})
}
}
Some important notes to make:
I am using the newest version of Parse (1.7.4) and FBSDK (4.1), so most other methods I've found online do not work anymore because certain functions or members have been removed since then.
The "func loginButton" is what I used for the FBSDKLoginButton, while the "#IBAction func facebookLoginDidPres" is for a regular UIButton I tried using for logging in. Based on what I've learned recently, I believe the UIButton method is the one I should go with, but that one leads to a Thread 1: Signal SIGABRT error stating:
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[PFFacebookUtils logInInBackgroundWithReadPermissions:block:]: unrecognized selector sent to class 0x10ed3ed80'
*** First throw call stack:
...
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) ""
So I placed an exception breakpoint and it ended at the end of the "logInInBackgroundWithReadPermissions" function in my IBAction with the console stating:
"[PFFacebookUtils logInInBackgroundWithReadPermissions:block:]: unrecognized selector sent to class 0x10dbe2db0 (lldb)"
The last detail I feel is worth mentioning is that my console states "parse: User already logged in" in when I run the app, however there is no User created when I check Parse. This is getting printed from the section under "check if the user is logged in" section of my LogInViewController's viewDidLoad function.
I will be forever grateful to anyone who can help me figure out this problem that's been puzzling me for far too long. Thank you in advance!
I deleted the old PFFacebookUtils Framework, but kept the PFFacebookUtilsV4 Framework, and that solved the problem for me! Hopefully that helps anyone else with this problem :)
I have the same problem, my solution is to define Login behaviour = Web
PFFacebookUtils.facebookLoginManager().loginBehavior = FBSDKLoginBehavior.Web
When I call this before call loginInBackground..., after clicking to the "OK" button, my application received call-back with a user (not nil) and PFUser.currentUser is updated with that user.

Resources