FirebaseUI "Sign in with email" does nothing when tapped - swift

I have the following code taken directly from this blog. This code successfully displays the FirebaseUI with Google sign In, Apple sign In, and Email sign in when I place the SignInViewUI into my view.
Google and Apple sign in both function correctly. Email sign in does nothing when tapped.
import Firebase
import FirebaseUI
import SwiftUI
typealias AM = AuthManager
class AuthManager : NSObject{
static let shared = AuthManager()
var authViewController : UIViewController {
return MyAuthViewController(authUI: FUIAuth.defaultAuthUI()!)
}
init(withNavigationBar : Bool = false){
FirebaseApp.configure()
super.init()
self.setupProviders()
}
private func setupProviders(){
let authUI = FUIAuth.defaultAuthUI()!
let providers: [FUIAuthProvider] = [
FUIGoogleAuth.init(authUI: authUI),
FUIOAuth.appleAuthProvider(),
FUIEmailAuth()]
authUI.providers = providers
}
}
extension AuthManager {
// an optional handler closure for error handling
func signOut(onError handler : ((Error?) -> Void)? = nil ){
do {
try FUIAuth.defaultAuthUI()?.signOut()
if let handler = handler {
handler(nil)
}
}
catch (let err){
if let handler = handler {
handler(err)
}
}
}
func isSignedIn() -> Bool {
if let _ = Firebase.Auth.auth().currentUser{
return true
}
return false
}
}
extension AuthManager {
func setAuthDelegate(_ delegate : FUIAuthDelegate){
FUIAuth.defaultAuthUI()?.delegate = delegate
}
}
class MyAuthViewController : FUIAuthPickerViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scrollView = view.subviews[0]
scrollView.backgroundColor = .clear
let contentView = scrollView.subviews[0]
contentView.backgroundColor = .clear
view.backgroundColor = .clear
}
}
struct SignInViewUI: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<SignInViewUI>) ->
UIViewController {
return AM.shared.authViewController
}
func updateUIViewController(_ uiViewController: UIViewController,
context: UIViewControllerRepresentableContext<SignInViewUI>) {
// empty
}
}

I believe this is something to do with a navigation controller being required for the Email sign in, based on the final comment on this GitHub issue.
Surrounding the SignInViewUI in a NavigationView allows the button to work.
Secondly, the FirebaseApp.configure() line must be removed from the AuthManager and placed into the AppDelegate application(_ application: UIApplication, didFinishLaunchingWithOptions ... method.

Related

How to listen for data change with #Published variable then reload tableView

The most difficult task I face is to know the correct terminology to search for. I'm used to SwiftUI for an easy way to build an app in the fastest time possible. With this project I have to use UIKit and for this specific task.
Inside a view controller I created a tableView:
private let tableView: UITableView = {
let table = UITableView()
table.register(ProfileCell.self, forCellReuseIdentifier: ProfileCell.identifier)
return table
}()
Later I reload the data inside viewDidLoad
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
try await viewModel.getProfiles()
// Here I reload the table when data comes in
self.tableView.reloadData()
} catch {
print(error)
}
}
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
}
So what is viewModel? In SwiftUI I'm used to having this inside a view struct:
#ObservedObject var viewModel = ProfilesViewModel()
..and that's what I have inside my view controller. I've searched for:
observedobject in uitableview
uitableview reload data on data change
..and more but noting useful for me to "pick up the pieces" with.
In same controller, I'm showMyViewControllerInACustomizedSheet which now uses UIHostingController:
private func showMyViewControllerInACustomizedSheet() {
// A SwiftUI view along with viewModel being passed in
let view = ProfilesMenu(viewModel: viewModel)
let viewControllerToPresent = UIHostingController(rootView: view)
if let sheet = viewControllerToPresent.sheetPresentationController {
sheet.detents = [.medium(), .large()]
sheet.largestUndimmedDetentIdentifier = .medium
sheet.prefersScrollingExpandsWhenScrolledToEdge = false
sheet.prefersEdgeAttachedInCompactHeight = true
sheet.widthFollowsPreferredContentSizeWhenEdgeAttached = true
}
present(viewControllerToPresent, animated: true, completion: nil)
}
For the ProfilesViewModel:
class ProfilesViewModel: ObservableObject {
// ProfilesResponse is omitted
#Published var profiles = [ProfilesResponse]()
public func getProfiles(endpoint: String? = nil) async throws -> Void {
// After getting the data, I set the profiles variable
self.profiles = [..]
}
}
Whenever I call try await viewModel.getProfiles(endpoint: "..."), from ProfileMenu, I'd like to reload the tableView. What additional setup is required?
In the comments, Vadian mentioned "Combine" where I did a Google search and found this. What works, for a basic demonstaration:
[..]
import Combine
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let viewModel = ProfilesViewModel()
private var cancellable: AnyCancellable?
override func viewDidLoad() {
super.viewDidLoad()
Task {
do {
try await viewModel.getProfiles()
// Remove this
// self.tableView.reloadData()
} catch {
print(error)
}
}
view.addSubview(tableView)
tableView.delegate = self
tableView.dataSource = self
// Add this
cancellable = viewModel.objectWillChange.sink(receiveValue: { [weak self] in
self?.render()
})
}
// Also add this
private func render() {
// TODO: Implement failures...
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
...
}
objectWillChange was the key to my problem.

Swift - How can cardParams be obtained from STPPaymentOptionsViewController

I want to complete the addition of new payment method that I implemented in this SO question. This save and reuse stripe tutorial shows that cardParams and billingDetails need to be passed to STPPaymentMethodParams. How to I get the cardParams and billingDetails from STPPaymentOptionsViewController?
This is the code that produce the STPPaymentOptionsViewController and then display the STPAddCardViewController when add card button is pressed.
import Foundation
import SwiftUI
import Stripe
struct PaymentOptionsView: UIViewControllerRepresentable {
func makeCoordinator() -> Coordinator {
Coordinator(self)
}
class Coordinator: NSObject, STPPaymentOptionsViewControllerDelegate {
var control: PaymentOptionsView
init(_ control: PaymentOptionsView) {
self.control = control
}
// Implement required delegate methods here:
func paymentOptionsViewControllerDidCancel(_ paymentOptionsViewController: STPPaymentOptionsViewController) {
}
func paymentOptionsViewControllerDidFinish(_ paymentOptionsViewController: STPPaymentOptionsViewController) {
}
func paymentOptionsViewController(_ paymentOptionsViewController: STPPaymentOptionsViewController, didFailToLoadWithError error: Error) {
}
}
func makeUIViewController(context: UIViewControllerRepresentableContext<PaymentOptionsView>) -> STPPaymentOptionsViewController {
let config = STPPaymentConfiguration()
// config.requiredBillingAddressFields = .none
config.appleMerchantIdentifier = "dummy-merchant-id"
return STPPaymentOptionsViewController(configuration: config, theme: STPTheme(), apiAdapter: STPCustomerContext(keyProvider: MyAPIClient()), delegate: context.coordinator)
}
func updateUIViewController(_ uiViewController: STPPaymentOptionsViewController, context: UIViewControllerRepresentableContext<PaymentOptionsView>) { }
}
STPPaymentOptionsViewController by design only returns you a PaymentMethod and not the raw card details.
Since the STPPaymentOptionsViewControllerDelegate returns you a STPPaymentOption, you can cast it to a STPPaymentMethod and then get the billingDetails for that PaymentMethod.
In your didSelect() delegate method, you can cast it like:
if let paymentMethod = paymentOption as? STPPaymentMethod {
print(paymentMethod.stripeId)
}
https://stripe.dev/stripe-ios/docs/Classes/STPPaymentMethod.html#/c:#M#Stripe#objc(cs)STPPaymentMethod(py)billingDetails

SwiftUI Game Center authentication doesn't prompt user to login

I have the below code to authenticate a local player in Game Center in my SwiftUI app. I want Game Center to prompt user to login if the player is not already login in but this doesn't happen.
class AppSettings: UINavigationController {
func authenticateUser() {
let localPlayer = GKLocalPlayer.local
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
}
}
}
What could be the problem? I also read about using UIViewControllerRepresentable somewhere in my class to integrate UIKit's ViewController into SwiftUI but I don't understand how I can use it.
Can someone help me out?
I didn't get anyone to answer my question correctly and after days of digging I found a solution. So I had to use the UIKit implementation like below and create a wrapper around it using UIViewControllerRepresentable in the GameCenterManager Struct. After that all I had to do was call GameCenterManager() inside my SwiftUI view in a ZStack and the job is done!
import SwiftUI
import UIKit
import GameKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
authenticateUser()
}
let localPlayer = GKLocalPlayer.local
func authenticateUser() {
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
if vc != nil {
self.present(vc!, animated: true, completion: nil)
}
if #available(iOS 14.0, *) {
GKAccessPoint.shared.location = .bottomLeading
GKAccessPoint.shared.showHighlights = true
GKAccessPoint.shared.isActive = self.localPlayer.isAuthenticated
// Fallback on earlier versions
}
}
}
}
struct GameCenterManager: UIViewControllerRepresentable {
func makeUIViewController(context: UIViewControllerRepresentableContext<GameCenterManager>) -> ViewController {
let viewController = ViewController()
return viewController
}
func updateUIViewController(_ uiViewController: ViewController, context: UIViewControllerRepresentableContext<GameCenterManager>) {
}
}
The authenticateHandler returns a UIViewController as well which you're not using:
#available(iOS 6.0, *)
open var authenticateHandler: ((UIViewController?, Error?) -> Void)?
You need to present it:
class AppSettings: UINavigationController {
func authenticateUser() {
let localPlayer = GKLocalPlayer.local
localPlayer.authenticateHandler = { vc, error in
guard error == nil else {
print(error?.localizedDescription ?? "")
return
}
if let vc = vc {
self.present(vc, animated: true, completion: nil)
}
}
}
}

didInititate method for Spotify IOS SDK is not calling even though called sessionManager.initiateSession()

I'm going through Spotify's authentication process and am requesting the scopes appRemoteControl for my app to control music and userReadCurrentlyPlaying for current song. I set up everything from the SPTConfiguration, SPTSessionManager, and SPTAppRemote, and their required delegate methods (SPTAppRemoteDelegate, SPTSessionManagerDelegate, SPTAppRemotePlayerStateDelegate) as well as initiating a session with the requested scopes whenever the user presses a button but I can't get the method
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
to trigger. The authentication process fully works as it goes into my spotify app and returns back to my application and plays a song from the configuration.playURI = "" , however, the method above never is called. I followed the spotify demo project but still does not work. Here is my full code
class LogInViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
let spotifyClientID = Constants.clientID
let spotifyRedirectURL = Constants.redirectURI
let tokenSwap = "https://***********.glitch.me/api/token"
let refresh = "https://***********.glitch.me/api/refresh_token"
lazy var configuration: SPTConfiguration = {
let configuration = SPTConfiguration(clientID: spotifyClientID, redirectURL: URL(string: "Lyrically://callback")!)
return configuration
}()
lazy var sessionManager: SPTSessionManager = {
let manager = SPTSessionManager(configuration: configuration, delegate: self)
if let tokenSwapURL = URL(string: tokenSwap), let tokenRefreshURL = URL(string: refresh) {
self.configuration.tokenSwapURL = tokenSwapURL
self.configuration.tokenRefreshURL = tokenRefreshURL
self.configuration.playURI = ""
}
return manager
}()
lazy var appRemote: SPTAppRemote = {
let appRemote = SPTAppRemote(configuration: configuration, logLevel: .debug)
appRemote.delegate = self
return appRemote
}()
#IBAction func logIn(_ sender: UIButton) {
let requestedScopes: SPTScope = [.appRemoteControl, .userReadCurrentlyPlaying]
sessionManager.initiateSession(with: requestedScopes, options: .default)
}
}
extension LogInViewController: SPTAppRemotePlayerStateDelegate {
func playerStateDidChange(_ playerState: SPTAppRemotePlayerState) {
print("state changed")
}
}
extension LogInViewController: SPTAppRemoteDelegate {
func appRemoteDidEstablishConnection(_ appRemote: SPTAppRemote) {
print("connected")
appRemote.playerAPI?.delegate = self
appRemote.playerAPI?.subscribe(toPlayerState: { (success, error) in
if let error = error {
print("Error subscribing to player state:" + error.localizedDescription)
}
})
}
func appRemote(_ appRemote: SPTAppRemote, didFailConnectionAttemptWithError error: Error?) {
print("failed")
}
func appRemote(_ appRemote: SPTAppRemote, didDisconnectWithError error: Error?) {
print("disconnected")
}
}
extension LogInViewController: SPTSessionManagerDelegate {
func sessionManager(manager: SPTSessionManager, didInitiate session: SPTSession) {
appRemote.connectionParameters.accessToken = session.accessToken
appRemote.connect()
print(session.accessToken)
}
func sessionManager(manager: SPTSessionManager, didFailWith error: Error) {
print("failed",error)
}
}
Figured it out. Had to get a hold of the sessionManager from the LogInViewController by making an instance of it
lazy var logInVC = LogInViewController()
then added this line of code into the openURLContexts method in scene delegate
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
print("Opened url")
guard let url = URLContexts.first?.url else {
return
}
logInVC.sessionManager.application(UIApplication.shared, open: url, options: [:])
}

Swift function textfield got focus OSX

Currently I am having multiple textfields in a view. If the user taps at one of them there should be a function responding to the event. Is there a way on how to do react (if a textfield got the focus)? I tried it with the NSTextFieldDelegate method but there is no appropriate function for this event.
This is how my code looks at the moment:
class ViewController: NSViewController, NSTextFieldDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let textField = NSTextField(frame: CGRectMake(10, 10, 37, 17))
textField.stringValue = "Label"
textField.bordered = false
textField.backgroundColor = NSColor.controlColor()
view.addSubview(textField)
textField.delegate = self
let textField2 = NSTextField(frame: CGRectMake(30, 30, 37, 17))
textField2.stringValue = "Label"
textField2.bordered = false
textField2.backgroundColor = NSColor.controlColor()
view.addSubview(textField2)
textField2.delegate = self
}
func control(control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
print("working") // this only works if the user enters a charakter
return true
}
}
The textShouldBeginEditing function only handles the event if the user tries to enter a character but this isn't what I want. It has to handle the event if he clicks on the textfield.
Any ideas, thanks a lot?
Edit
func myAction(sender: NSView)
{
print("aktuell: \(sender)")
currentObject = sender
}
This is the function I want to call.
1) Create a subclass of NSTextField.
import Cocoa
class MyTextField: NSTextField {
override func mouseDown(theEvent:NSEvent) {
let viewController:ViewController = ViewController()
viewController.textFieldClicked()
}
}
2) With Interface building, select the text field you want to have a focus on. Navigate to Custom Class on the right pane. Then set the class of the text field to the one you have just created.
3) The following is an example for ViewController.
import Cocoa
class ViewController: NSViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldClicked() -> Void {
print("You've clicked on me!")
}
}
4) Adding text fields programmatically...
import Cocoa
class ViewController: NSViewController {
let myField:MyTextField = MyTextField()
override func viewDidLoad() {
super.viewDidLoad()
//let myField:MyTextField = MyTextField()
myField.setFrameOrigin(NSMakePoint(20,70))
myField.setFrameSize(NSMakeSize(120,22))
let textField:NSTextField = NSTextField()
textField.setFrameOrigin(NSMakePoint(20,40))
textField.setFrameSize(NSMakeSize(120,22))
self.view.addSubview(myField)
self.view.addSubview(textField)
}
override var representedObject: AnyObject? {
didSet {
// Update the view, if already loaded.
}
}
func textFieldClicked() -> Void {
print("You've clicked on me!")
}
}
I know it’s been answered some while ago but I did eventually find this solution for macOS in Swift 3 (it doesn’t work for Swift 4 unfortunately) which notifies when a textfield is clicked inside (and for each key stroke).
Add this delegate to your class:-
NSTextFieldDelegate
In viewDidLoad() add these:-
imputTextField.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(textDidChange(_:)), name: Notification.Name.NSTextViewDidChangeSelection, object: nil)
Then add this function:-
func textDidChange(_ notification: Notification) {
print("Its come here textDidChange")
guard (notification.object as? NSTextView) != nil else { return }
let numberOfCharatersInTextfield: Int = textFieldCell.accessibilityNumberOfCharacters()
print("numberOfCharatersInTextfield = \(numberOfCharatersInTextfield)")
}
Hope this helps others.