peterfriese / MakeItSo

This is the source code for Make It So, the sample app accompanying my blog post "Replicating the iOS Reminders App Using SwiftUI and Firebase"

Home Page:https://twitter.com/peterfriese/status/1453467058302291975

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Having problems to update ios13 code to ios14 (problems in FirebaseAuth + @main

mateusnevoli opened this issue · comments

Hi Peter, its me again. Im having a problem and didn't find an answer anywhere. First of all, I would like to apologize you
for posting this question here, but I didn't know where to post. After implementing some iOS 14 code, I updated my entire code to iOS 14 (before it was 13). But, with it came lot of error messages, with which I accidentally delete some stuff that stopped my code from updating when I changed it (it sucks that I didn't have any backup, and the ones I have appears to inherit the same errors). Then, I decided to create a new project, and add everything back again. However, the overall appearance of Xcode changed and I'm having problems in fixing them. The first one in related to the new @main struct (mine called MedicalApp). Before,in my code, the initial view was ContenView and it was exactly like this:

struct ContentView: View {

@EnvironmentObject var session: SessionStore

func getUser() {
    session.listen()
}
var body: some View {
    Group {
        if (session.session != nil) {
            HomeView()
        }
        else {
            SigninOrSignUp()
        }
    }
    .onAppear(perform: getUser)
}
}

Now, it appears that the main struct has changed to "projectName"App. Mine, is this one:

@main
 struct MedicalApp: App{
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene{
    WindowGroup{
        ContentView()
    }
}
}

With the same ContentView code as before.

These are my SessionStore, AppDelegate, SceneDelegate and SignInOrSignUpView that I copied exactly like the other code (you might have them from when I shared my code with you):

class SessionStore: ObservableObject{

   var didChange = PassthroughSubject<SessionStore, Never>()
   var session: User? {didSet {self.didChange.send(self)}}
  @Published var handle: AuthStateDidChangeListenerHandle?



   func listen() {
    
    handle = Auth.auth().addStateDidChangeListener({ (auth, user) in
        if let user = user {
            self.session = User(uid: user.uid, email: user.email)
        }
        else {
            self.session = nil
        }
    })
    }

   func signUp(email: String, password: String, handler: @escaping AuthDataResultCallback) {
    
    Auth.auth().createUser(withEmail: email, password: password, completion: handler)
   }



   func sigIn(email: String, password: String, handler: @escaping AuthDataResultCallback){
    
      Auth.auth().signIn(withEmail: email, password: password, completion: handler)
    
   }

  func signOut() {
    
    do {
        try Auth.auth().signOut()
        self.session = nil
    }
    catch  {
        print("Erro ao sair")
    }
}
func showError(_ message: String) {
    
}

func unbind() {
    
    if let handle = handle{
        Auth.auth().removeStateDidChangeListener(handle)
    }
}
deinit {
    unbind()
  }


   }

  class AppDelegate: UIResponder, UIApplicationDelegate , GIDSignInDelegate {

     var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions  launchOptions:      [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
      FirebaseApp.configure()
    GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
    GIDSignIn.sharedInstance().delegate = self

    return true
    }


           func application(_ application: UIApplication, open url: URL, options:   [UIApplication.OpenURLOptionsKey : Any])
    -> Bool {
   return GIDSignIn.sharedInstance().handle(url)
  }

     func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error?)      {
  // ...
  if let error = error {
    print(error.localizedDescription)
    return
  }

  guard let authentication = user.authentication else { return }
  let credential = GoogleAuthProvider.credential(withIDToken: authentication.idToken,
                                                    accessToken: authentication.accessToken)
    Auth.auth().signIn(with: credential) { (res, err) in
        if err != nil{
            print((err?.localizedDescription)!)
            return
        }
        print("usuário=" + (res?.user.email)!)
    }
    
    
}

func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
    // Perform any operations when the user disconnects from app here.
    // ...
}

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
}
func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
}
  }

 class SceneDelegate: UIResponder, UIWindowSceneDelegate {

var window: UIWindow?


func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    let contentView = ContentView()
    if let windowScene = scene as? UIWindowScene {
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: contentView.environmentObject(SessionStore()))
        self.window = window
        window.makeKeyAndVisible()
    }
}

func sceneDidDisconnect(_ scene: UIScene) {
    
}

func sceneDidBecomeActive(_ scene: UIScene) {
   
}

func sceneWillResignActive(_ scene: UIScene) {
    
}

func sceneWillEnterForeground(_ scene: UIScene) {
   
}

func sceneDidEnterBackground(_ scene: UIScene) {
    
}
 }



struct SigninOrSignUp: View {

var body: some View {
    
    ZStack{
               LinearGradient(gradient: .init(colors: [Color("Color"),Color("Color1"),Color("Color2")]), startPoint: .top
            , endPoint: .bottom)
            .edgesIgnoringSafeArea(.all)
        
        if UIScreen.main.bounds.height > 800{
            
            SignView()
        }
        else{
            
            ScrollView(.vertical, showsIndicators: false) {
                
                SignView()
            }
        }
    
    }
 }
  }

*SignView is the main view for Signin and Signup

*Above AppDelegate, I had @UIApplicationMain. It had to be deleted because there was an error saying there were multiple main (possibly referring to @main in struct MedicalApp: App).

The building succeeds, but the screen starts all white and then turns to all black.

Questions:
Do I need to maintain "projectName"App? If I delete it, how to turn ContentView the main one (tried @main but didn't work because it needed a main static function)?
How to fix these problem? How to make them work again?

--> If you still have the code I shared with you it would be great if you shared it back with me, as I deleted the repo because it was public.

After some time, this appeared on output:
2020-11-06 18:26:14.273193-0300 MedicalApp[22684:253294] [] nw_protocol_get_quic_image_block_invoke dlopen libquic failed
2020-11-06 18:26:15.830546-0300 MedicalApp[22684:253306] 7.0.0 - [Firebase/Analytics][I-ACS023007] Analytics v.7.0.0 started
2020-11-06 18:26:16.169322-0300 MedicalApp[22684:253306] 7.0.0 - [Firebase/Analytics][I-ACS023008] To enable debug logging set the following application argument: -FIRAnalyticsDebugEnabled (see "gooleLink")
2020-11-06 18:26:22.776226-0300 MedicalApp[22684:253306] 7.0.0 - [Firebase/Analytics][I-ACS800023] No pending snapshot to activate. SDK name: app_measurement
2020-11-06 18:26:29.967694-0300 MedicalApp[22684:253350] 7.0.0 - [Firebase/Analytics][I-ACS023012] Analytics collection enabled
2020-11-06 18:26:29.977395-0300 MedicalApp[22684:253350] 7.0.0 - [Firebase/Analytics][I-ACS023220] Analytics screen reporting is enabled. Call +[FIRAnalytics logEventWithName:FIREventScreenView parameters:] to log a screen view event. To disable automatic screen reporting, set the flag FirebaseAutomaticScreenReportingEnabled to NO (boolean) in the Info.plist

Already fixed it

I'm glad to hear you were able to resolve the issue. I will close this issue now.

First of all, I would like to apologize you for posting this question here, but I didn't know where to post.

My advice is to post where it makes most sense:

  • If you think it's a bug, use the GitHub issue tracker of the project in question. If it is a bug in any of my projects, file a bug against the project. If it's a bug in Firebase, find the respective Firebase project and file it there.
  • If it's a question, ask on StackOverflow. Please read How do I ask a good question?!

In addition to that, please note that you can create private projects n GitHub. That's a great way to keep track of your project, even if you're just working as a solo developer. You can even add people to your private repos to collaborate and discuss code that you'd rather not share with the general public. You can even make a once-public project private again:

Screenshot 2020-11-08 at 19 34 11

GitHub has a ton of help content - by reading into it just for a few minutes a day you'll become a pro in no time. I'd also recommend Pro Git by Scott Chacon - it's still a great resource to understand git.