Firebase Mobile not logging in after authentication - ios

How to prevent the account from automatically logging in after firebase SMS authentication and registration, I tried to delete ->Auth.auth().signIn(with: credential) { _, error in completion(error) } , but the firebase account registration was unsuccessful
#IBAction func startVerification() {
let configuration = Configuration(requestCode: { phone, completion in
PhoneAuthProvider.provider().verifyPhoneNumber(phone, uiDelegate: nil, completion: completion)
}, signIn: { verificationID, verificationCode, completion in
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)
Auth.auth().signIn(with: credential) { _, error in completion(error) }
})
let vc = PhoneVerificationController(configuration: configuration)
vc.delegate = self
present(vc, animated: true)
}
}

Related

Resend Code using Firebase Authentication in Swift

As there is no direct method to resend code once the code has already been sent , I am trying to resend it once again with following method :
func sendOTPGetVerfID(phoneNum: String, completion: #escaping((_ verificationID: String?, _ error: Error?) -> Void)) {
PhoneAuthProvider.provider().verifyPhoneNumber( phoneNum , uiDelegate: nil) { (verificationID, error) in
if let error = error {
QL1(error.localizedDescription)
completion(nil, error)
return
}
// Sign in using the verificationID and the code sent to the user
// ...
QL1("VerificationID : \(verificationID ?? "")")
completion(verificationID,nil)
}
}
Issue here is, I am not able to receive the verificationID second time, calling the above method
Any help appreciated
Call requestOtp() method on resend OTP button click.
import FirebaseAuth
func requestOtp() {
let phNo = "Your phone number"
PhoneAuthProvider.provider().verifyPhoneNumber(phNo, uiDelegate: nil) { (verificationID, error) in
if let error = error {
print(error.localizedDescription)
return
}
// Sign in using the verificationid and the code sent to the user
// ...
UserDefaults.standard.set(verificationID, forKey: "authVerificationID")
}
}
Verify Code with Auth:
func verifyNumberWith(verificationCode: String) {
let verificationID=UserDefaults.standard.string(forKey:"authVerificationID")
let credential = PhoneAuthProvider.provider().credential(
withVerificationID: verificationID ?? "",
verificationCode: verificationCode)
Auth.auth().signIn(with: credential) { (authResult, error) in
//Do your actions.
}
}

How do I segue back to the main storyboard after verifying app with Firebase?

I am using a third party view controller to verify my app with firebase.
It works perfectly to create a user using their phone number but after creating an account, it just stays on the input phone number storyboard. How can I have it segue back to the main.storyboard after a phone number is verified.
The third party is: https://github.com/appwise-labs/PhoneVerificationController/blob/master/README.md
Here is the code from my view controller.swift:
#IBAction func onLoginButtonPressed(_ sender: Any) {
let configuration = Configuration(requestCode: { phone, completion in
PhoneAuthProvider.provider().verifyPhoneNumber(phone, uiDelegate: nil, completion: completion)
}, signIn: { verificationID, verificationCode, completion in
let credential = PhoneAuthProvider.provider().credential(withVerificationID: verificationID, verificationCode: verificationCode)
Auth.auth().signInAndRetrieveData(with: credential) { _, error in completion(error) }
})
let vc = PhoneVerificationController(configuration: configuration)
vc.delegate = self as? PhoneVerificationDelegate
present(vc, animated: true)
}
Use the delegate methods
extension ViewController: PhoneVerificationDelegate {
func cancelled(_ controller: PhoneVerificationController) {
print("Cancelled verification")
controller.dismiss(animated: true)
}
func verified(_ phoneNumber: String, controller: PhoneVerificationController) {
print("Verified phone \(phoneNumber)")
controller.dismiss(animated: true)
}
}
And replace this
vc.delegate = self as? PhoneVerificationDelegate
with
vc.delegate = self

Firebase Login URL Fetch Config Error

I am trying to have my login function for firebase run after updating it, but the function is nil and I am getting the following messages:
Cannot create a URL to fetch a configuration with empty app instance ID or empty platform (app instance, platform): (nil), ios
[Firebase/Analytics][I-ACS023125] Unable to get configuration. Invalid server URL.
My code is as follows:
#IBAction func Login(sender: AnyObject) {
let email = self._Email.text!
let password = self._Password.text!
print("below is the email")
print(email)
print("below is the password")
print(password)
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error == nil {
print("Successful login")
if user!.isEmailVerified{
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ProfileView") as! ProfileView
self.present(vc, animated: true, completion: nil)
} else {
print("nil is hitting")
}
} else {
print("Some nil error")
}
}
}

firebase login function not running

I am trying to run the login function for firebase, which worked fine, but after updating swift version it doesn't work. When I check both if the error is nil and not nil neither print statement runs, but the prints before and after does. Does anyone know why this would not be running, but also not throwing error?
Below is the code:
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { user, error in
if error == nil {
print("Successful login")
if user!.isEmailVerified {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ProfileView") as! ProfileView
self.present(vc, animated: true, completion: nil)
} else {
print("nil is hitting")
}
}
})
print("done running login")
Use this Auth instead of FIRAuth.
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
// ...
}
To know more read
Firebase Documention
To signIn in Firebase, you need to use Auth instead FIRAuth
Auth.auth().signIn(withEmail: "email#email.com",
password: "123456") { (user, error) in
if error == nil {
print("successful login")
}
}
Auth.auth().signIn(withEmail: email!, password: password!) { (user, error) in
if let error = error { print("Enter Valid email and password")
}else{
if Auth.auth().currentUser!.isEmailVerified == true{
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ProfileView") as! ProfileView
self.present(vc, animated: true, completion: nil)}}}

Apple Pay and Stripe: Token not being sent to Stripe

Set up Apple Pay in my app and it seems to work fine when running on device. Using Stripe as the payment processor but it is not sending the token to Stripe, but seems to be charging the credit card listed in my iPhone's digital wallet.
The problem I am having is that once I press the "Pay with Touch ID", I get a check mark in my Apple Pay sheet but the following page appears in Xcode:
Code for Apple Pay & Stripe
var paymentSucceeded: Bool = false
func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController,
didAuthorizePayment payment: PKPayment, completion: #escaping (PKPaymentAuthorizationStatus) -> Void) {
STPAPIClient.shared().createToken(with: payment) { (token, error) in
print("I am here")
if error != nil {
completion(.failure)
print("failed")
} else {
self.paymentSucceeded = true
completion(.success)
print("woohoo")
}
self.createBackendCharge(with: token!, completion: completion)
print("created Backend Charge")
self.postStripeToken(token: token!)
print("posted stripe token")
}
} // paymentAuthorizationViewController( didAuthorizePayment )
func createBackendCharge(with token: STPToken, completion: #escaping (_: PKPaymentAuthorizationStatus) -> Void) {
//We are printing Stripe token here, you can charge the Credit Card using this token from your backend.
print("Stripe Token is \(token)")
completion(.success)
} // createBackendCharge func
func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
controller.dismiss(animated: true, completion: {
if (self.paymentSucceeded) {
// show a receipt page
}
})
} // paymentAuthorizationViewControllerDidFinish()
#IBAction func applePayPressed(_ sender: UIButton) {
// we have already accepted the request from viewDriverBids
// all that remains is to complete payment
print("enable apple pay")
// send user to Apple Pay to make payment
let paymentNetworks = [PKPaymentNetwork.visa, .masterCard, .interac, .discover, .amex]
if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks) {
paymentRequest = PKPaymentRequest()
paymentRequest.currencyCode = "CAD"
paymentRequest.countryCode = "CA"
paymentRequest.merchantIdentifier = "merchant.com.xxx"
paymentRequest.supportedNetworks = paymentNetworks
paymentRequest.merchantCapabilities = .capability3DS
paymentRequest.requiredShippingAddressFields = [.all]
paymentRequest.paymentSummaryItems = self.rydes()
let applePayVC = PKPaymentAuthorizationViewController(paymentRequest: paymentRequest)
applePayVC.delegate = self
self.present(applePayVC, animated: true, completion: {
rRydeHandler.Instance.completeApplePay()
self.paymentComplete = true
self.updateDriverInfoView()
})
} else {
print("Tell the user they need to set up Apple Pay!")
}
} // applePayPressed func ACTION
backend server func
func postStripeToken(token: STPToken) {
let URL = "http://localhost/donate/payment.php"
let params = ["stripeToken": token.tokenId,
"amount": Int(self.driverInfoView.rydeFare.text!)!,
"currency": "cad",
"description": self.riderName] as [String : Any]
let manager = AFHTTPSessionManager()
manager.post(URL, parameters: params, success: { (operation, responseObject) -> Void in
if let response = responseObject as? [String: String] {
let alertController = UIAlertController(title: response["status"], message: response["message"], preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .default, handler: nil)
alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}) { (operation, error) -> Void in
self.handleError(error as NSError)
print(error)
}
}
How can I resolve this issue?
Enable exception breakpoints then Xcode should crash on the line that is causing the issue.
It is almost certainly caused by one of the ! in your code.
Force unwrapping values is very dangerous. It's always better and safer to unwrap it in a guard let or if let.

Resources