Swift Firebase Twitter Login: Unable to get credential - swift

I am implementing Firebase Authentication with Twitter login and I followed the docs but wasn't able to get any response from getCredentialWith. Other SO post on this topic is outdated as most still uses TwitterKit, which has already stopped being supported.
My implementation so far:
//At viewDidLoad()
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Login", style: .plain, target: self, action: #selector(loginWithTwitter))
#objc func loginWithTwitter() {
print("Login button tapped")
let provider = OAuthProvider(providerID: "twitter.com")
provider.getCredentialWith(nil) { credential, error in
print(2) // <== Not printed
if error != nil {
// Handle error.
print("Err", error)
}
if let credential = credential {
Auth.auth().signIn(with: credential) { authResult, error in
print(3) // <== Not printed
if error != nil {
// Handle error.
print("Err auth", error)
}
if let authResult = authResult {
print(authResult.credential)
}
}
}
}
Oddly, the above code, as copy and pasted from the docs, doesn't seem to return to print 2.
I have ensured that I have done the following:
Added URL schemes to the Info tab
Enabled Twitter sign in on Firebase Authentication
Added the necessary API key and secret key on Firebase Auth
Added callback URL to Twitter developer dashboard
What am I missing?

I managed to solve it by:
Adding a website URL to the authentication settings in Twitter Developer portal
Moving let provider = OAuthProvider(providerID: "twitter.com") to a global variable

Related

How to Sign out and Delete Users Register By FirebaseUI Swift 5

I want to give my app the ability to Log out/delete the user and when I type this code
#IBAction func deleteTheAccountButtonHasBeenTapped(_ sender: Any) {
let user = Auth.auth().currentUser
var credential: AuthCredential
user?.reauthenticateAndRetrieveData(with: credential, completion: {(authResult, error) in
if let error = error {
// An error happened.
print(error)
}else{
//user re-authenticated
user?.delete { error in
if let error = error {
// An error happened.
print(error)
} else {
// Account deleted.
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "LoginVC") as! LoginVC
self.present(vc, animated:true, completion:nil)
}
}
}
})
}
I got this error:
Variable 'credential' used before being initialized
any one can help me?
The error message is pretty explicit: you're using credential before you initialized it.
In order to delete the user, you need to first reauthenticate them, as shown in the documentation on reauthenticating the user. Your version doesn't implement this comment from that code:
// Prompt the user to re-provide their sign-in credentials
How to reauthenticate the user depends on the provider. For example for email/password, you'd get them with:
credential = EmailAuthProvider.credential(withEmail: email, password: password)
A handy place to find similar snippets for other providers is in the documentation on linking accounts.

Google Classroom API integration with swift

I want to link my iOS app with Google Classroom on swift. My current goal is to be able to get a list of all the courses I am enrolled in.
Here is the code I am currently using
func googleClassroomList() {
//let sharedInstance = GIDSignIn.sharedInstance()
//let handler = sharedInstance
googleClassroomService.apiKey = "AIzaSyBOGamjhRuu45T2jT7Qa3LmtntSwgIxeqo"
let query = GTLRClassroomQuery_CoursesList.query()
query.pageSize = 1000
let classQuery = googleClassroomService.executeQuery(query, completionHandler: { ticket , fileList, error in
if error != nil {
let message = "Error: \(error?.localizedDescription ?? "")"
print(message)
} else {
if let list = fileList as? GTLRClassroomQuery_CoursesList {
self.fileList = list
print("List: \(list)")
}
else {
print("Error: response is not a file list")
}
}
}
)
}
Here is the error message:
Error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
I don't understand where I attach the OAuth access token, I tried putting it under apiKey but I don't really understand what I am supposed to do. For reference, I am using this auth scope. "https://www.googleapis.com/auth/classroom.courses"
First you have to sign-in using Google, and Google will manage the OAuth 2.0 token for you.
Here you have the instructions:
https://developers.google.com/identity/sign-in/ios/sign-in?ver=swift
Also make sure to set the service.authorizer property when you are actually signed in:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
withError error: Error!) {
guard let user = user else {
return
}
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.setLoggedOut(loggedOut: false)
self.myClassroom.service.authorizer = user.authentication.fetcherAuthorizer()
self.showClassroomClasses()
}

Firebase not storing logged in user

Was working with Firebase for almost half year now and never had this issue. Using code just like before to create new user, he shows up in console, when i close app i can sign in but using same code as always it keeps prompting me for password. In first VC i have:
if let user = Auth.auth().currentUser {
performSegue(withIdentifier: "authorized", sender: self)
}
Which will check if there is auth token stored and perform segue to loading screen. However this never happens. The code is ran but doesn't do anything, no errors in compiler and no errors in console.
EDIT 1: also tried to create new project where i rewrote all the code getting same result, but my other project works without any issues, also i'm able to do anything else besides this using firebase such as access Firestore just not storing the user, went over all the documentation but couldn't find any solution.
EDIT 2: sign in code
if(email.text != "" && password.text != ""){
Auth.auth().signIn(withEmail: email.text!, password: password.text!) { user, error in
if(error == nil && user != nil) {
userID = (Auth.auth().currentUser?.uid)!
print("Signed in as: \(userID)")
self.performSegue(withIdentifier: "load", sender: self)
} else {
print("Error found: \(error?.localizedDescription)")
}
}
}
Solution:
DispatchQueue.main.async(){
if let user = Auth.auth().currentUser {
userID = (Auth.auth().currentUser?.uid)!
self.performSegue(withIdentifier: "authorized", sender: self)
}
}
Loaded with async so firebase will configure before checking for auth
The issue is likely that you are calling your code before firebase has properly initialized. I recommend using the entry view controller's viewDidAppear for things such as these. If you were using viewDidLoad, it is likely that firebase did not load yet.

How do you connect to AWS Cognito in Swift for user signing up and logging in?

I'm going to start this question by apologizing for such an open ended question, but I am really struggling and all the documentation is outdated.
Amazon's provided sample app hasn't been updated and I get nothing but errors when attempting to run it. I have a login page setup and ready to go with email and password, and I have tried this code:
#IBAction func signInButtonTouched(sender: UIButton) {
if (emailTextField.text != nil) && (passwordTextField.text != nil) {
let user = (UIApplication.sharedApplication().delegate as! AppDelegate).userPool!.getUser(emailTextField.text!)
user.getSession(emailTextField.text!, password: passwordTextField.text!, validationData: nil, scopes: nil).continueWithExecutor(AWSExecutor.mainThreadExecutor(), withBlock: {
(task:AWSTask!) -> AnyObject! in
if task.error == nil {
// user is logged in - show logged in UI
} else {
// error
}
return nil
})
} else {
// email or password not set
}
}
but unfortunately I'm getting App Delegate has no member "userPool" errors. It does though! I am very new at this, and I have searched github and read through all of Amazon's samples, but the documentation is either in Objective-C, or outdated and doesn't work properly.
Any help with this would be vastly appreciated.

Unable to pass Facebook User properties to Firebase FIRAuth in Swift 3

I'm using the following function to login a User with a Facebook Token and the Firebase FIRAuth function. There is no error and no print of email property. As if the function wouldn't be called.
var login = FBSDKLoginManager()
#IBOutlet weak var fbBtnPressed: UIButton!
#IBAction func fbBtnPressed(_ sender: AnyObject) {
login.logIn(withReadPermissions: ["public_profile", "email", "user_friends"], from: self) { (FBSDKLoginManagerLoginResult, Error) in
if Error != nil {
print("The login with Facebook don't working. Erro: \(Error)")
} else {
let accessToken = FBSDKAccessToken.current().tokenString
print("Login with Facebook ok. \(accessToken)")
let credential = FIRFacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString)
FIRAuth.auth()?.signIn(with: credential) { (email, error) in
if (error != nil) {
print("The login in the Firebase broke \(error)")
} else {
print("Login in the Firebase ok \(email)")
}
}
}
}
}
After a lot of research, it seems to be a change in Swift3 in combination with the Keychain swap.
You have to enable the Keychange Sharing in your project under capabilities.