Black screen flashes between Launch and first ViewController in SceneDelegate - swift

I am using SceneDelegate.swift to decide which ViewController is shown with this code:
guard let windowScene = (scene as? UIWindowScene) else { return }
if Auth.auth().currentUser != nil {
AuthenticationService.automaticSignIn(onSuccess: {
let window = UIWindow(windowScene: windowScene)
self.window = window
let mainstoryboard:UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
let newViewcontroller:UIViewController = mainstoryboard.instantiateViewController(withIdentifier: "TabBarControllerID") as! TabBarController
window.rootViewController = newViewcontroller
window.makeKeyAndVisible()
}, onError: {
let window = UIWindow(windowScene: windowScene)
self.window = window
let mainstoryboard:UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
let newViewcontroller:UIViewController = mainstoryboard.instantiateViewController(withIdentifier: "LoginViewControllerID") as! LoginViewController
window.rootViewController = newViewcontroller
window.makeKeyAndVisible()
})
} else {
let window = UIWindow(windowScene: windowScene)
self.window = window
let mainstoryboard:UIStoryboard = UIStoryboard(name: "Login", bundle: nil)
let newViewcontroller:UIViewController = mainstoryboard.instantiateViewController(withIdentifier: "LoginViewControllerID") as! LoginViewController
window.rootViewController = newViewcontroller
window.makeKeyAndVisible()
}
}
Between the transition, a black screen appears (in my .gif for about 0.2 seconds), depending on the loading time. Sorry for the bad quality and the short duration, but you will see it:
Where does this black screen come from?

try to change this line:-
self.window!.rootViewController = UINavigationController(rootViewController: DashboardVC)
self.window!.makeKeyAndVisible()

The issue seems to be caused by a 'gap' in the presentation between the launch-storyboard and the window that is made visible. The appleIDProvider is async.
A workaround, rather than a fix, is to present a temporary View (with the same color or content as your launch-storyboard) and replace it once authorization is done;
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = scene as? UIWindowScene else { return }
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: TempView())
self.window = window
window.makeKeyAndVisible()
let user = User.shared
let appleIDProvider = ASAuthorizationAppleIDProvider()
appleIDProvider.getCredentialState(forUserID: user.id) { (credentialState, error) in
switch credentialState {
case .authorized:
DispatchQueue.main.async {
user.authenticated = true
window.rootViewController = UIHostingController(rootView: HomeView(showAlert: false, showSendview: false, showAccountview: false))
}
default:
DispatchQueue.main.async {
user.authenticated = false
window.rootViewController = UIHostingController(rootView: SignInView().environment(\.window, window))
}
}
}
}

Related

How to change rootViewController in swift?

I am working on an application in which there is no login logout feature. When user opens the application he sees main screen. Now there is an option in setting page named as Pin Lock application. When user select this option a PinScreen comes(like OTP Screen) then user sets the Pin. After that When user closes the application the Pin lock screen comes first asking user to enter pin.
So how can i do that?
if UserDefaults.standard.bool(forKey: "LoggedIn") == false {
let story = UIStoryboard(name: "Main", bundle:nil)
let vc = story.instantiateViewController(withIdentifier: "EnterPin") as! UINavigationController
UIApplication.shared.windows.first?.rootViewController = vc
UIApplication.shared.windows.first?.makeKeyAndVisible()
let enterPinViewController = self.storyboard.instantiateViewController(identifier: "EnterPinViewController") as! EnterPinViewController
self.navigationController.present(enterPinViewController, animated: true, completion: nil)
} else if UserDefaults.standard.bool(forKey: "LoggedIn") == true {
let story = UIStoryboard(name: "Main", bundle:nil)
let vc = story.instantiateViewController(withIdentifier: "MainController") as! UINavigationController
UIApplication.shared.windows.first?.rootViewController = vc
UIApplication.shared.windows.first?.makeKeyAndVisible()
let mainViewController = self.storyboard.instantiateViewController(identifier: "ViewController") as! ViewController
self.navigationController.present(mainViewController, animated: true, completion: nil)
}
Currently i am setting UserDefaults value as true and false and saving Pin in UserDefaults itself. I have tried changing rootViewController but nothing happening means every time main screen is coming instead of Pin Screen.
First you need to get the Window from SceneDelegate and use that window for rootViewController.
Suggestion: Whenever we are using rootViewController then no need to do present and push thing it will automatically set as a main home viewcontroller(Intial viewController)
let window = (UIApplication.shared.connectedScenes.first!.delegate as! SceneDelegate).window
let storyboard = UIStoryboard(name: "Main", bundle:nil)
if UserDefaults.standard.bool(forKey: "LoggedIn") == false {
let vc =storyboard.instantiateViewController(withIdentifier: "EnterPin") as! UINavigationController
window?.rootViewController = vc
window?.makeKeyAndVisible()
} else if UserDefaults.standard.bool(forKey: "LoggedIn") == true {
let vc =storyboard.instantiateViewController(withIdentifier: "MainController") as! UINavigationController
window?.rootViewController = vc
window?.makeKeyAndVisible()
}
I suggest you do all this things in SceneDelegate file
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let scene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: scene)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
if UserDefaults.standard.bool(forKey: "LoggedIn") == false {
let vc = storyboard.instantiateViewController(withIdentifier: "EnterPin") as! UINavigationController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
} else if UserDefaults.standard.bool(forKey: "LoggedIn") == true {
let vc = storyboard.instantiateViewController(withIdentifier: "MainController") as! UINavigationController
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
}
I Hope it is helpful for you!
let viewController = MainViewController()
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
guard let window = appDelegate.window else {
return
}
window.rootViewController = viewController

How can I add cover vertical animation while changing rootViewController

I can add animation from options. But none of them are cover vertical. How can add cover vertical animation ?
guard let window = UIApplication.shared.windows.filter({$0.isKeyWindow}).first else {
return
}
guard let rootViewController = window.rootViewController else {
return
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "x") as! xTabBarController
vc.view.frame = rootViewController.view.frame
vc.view.layoutIfNeeded()
UIView.transition(with: window, duration: 0.2, options: .transitionCrossDissolve, animations: {
window.rootViewController = vc
}, completion: { completed in
})

Autologin functionality in swift

I want to implement Autologin functionality. when i will open my app it will go to "loginViewController".And after login i am saving the login id to UserDefaults.And for the second time if UserDefaults has the value the ift will go to "SlideMenuController". i have written the code in "sceneDelegate". The code is-
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
if let logId = UserDefaults.standard.value(forKey: "loginId") {
goToPlayerMenu()
}
guard let _ = (scene as? UIWindowScene) else { return }
}
func goToPlayerMenu() {
let storyboard = UIStoryboard(name: "PlayerHomeScreen", bundle: nil)
let homeViewController = storyboard.instantiateViewController(withIdentifier: "PlayerHomeViewController") as! PlayerHomeViewController
let menuViewController = storyboard.instantiateViewController(withIdentifier: "PlayerMenuViewController") as! PlayerMenuViewController
let nvc: UINavigationController = UINavigationController(rootViewController: homeViewController)
nvc.navigationBar.barTintColor = UIColor.black
nvc.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
nvc.navigationItem.leftBarButtonItem?.tintColor = .white
nvc.navigationBar.tintColor = UIColor.black
//menuViewController.homeViewController = nvc
let slideMneu = SlideMenuController.init(mainViewController: nvc, leftMenuViewController: menuViewController)
slideMneu.delegate = homeViewController as? SlideMenuControllerDelegate
slideMneu.changeLeftViewWidth(UIScreen.main.bounds.width-40)
slideMneu.automaticallyAdjustsScrollViewInsets = true
self.window?.rootViewController = slideMneu
}
Now i want to go to Login viewcontroller, if i will logout of the app. But as my rootViewController is "slideMneu". i am unable to go to the "loginViewController". is there any option to go to the "loginViewController" after logout?
my logout function is-
func logout(){
UserDefaults.standard.removeObject(forKey: "customer_id")
UserDefaults.standard.removeObject(forKey: "isContributor")
FUser.logOutCurrentUser { (logout) in
if logout == true{
print("DEBUG: Logout completed")
}
}
let Alert = UIAlertController(title:Common.sharedInstance().TITLE_ALERT, message:Common.sharedInstance().CONFIRM_ALERT, preferredStyle: .alert)
let OKButtonAction = UIAlertAction(title: Common.sharedInstance().ALERT_YES, style: UIAlertAction.Style.default) { (action:UIAlertAction!) in
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let LoginViewController = storyBoard.instantiateViewController(withIdentifier: "LoginViewController") as? LoginViewController
self.navigationController?.pushViewController(LoginViewController!, animated: true)
// self.navigationController?.popViewController(animated: true)
}
let Cancel = UIAlertAction(title:Common.sharedInstance().NO, style: .default, handler: nil)
Alert.addAction(OKButtonAction)
Alert.addAction(Cancel)
self.present(Alert, animated: true, completion:nil)
All codes comes from my project
1.Where you set you Keywindow RootViewController
let navigator = Container.shared.resolve(INavigator.self)!
let localStorageService = Container.shared.resolve(ILocalStorageService.self)!
// if you store login user key or not
if localStorageService.isKeyExist(key: Configs.KEY_USER) {
// if there is key,then goes to main page
navigator.switchRoot(keyWindow: window!, scene: .main(viewModel: MainTabBarViewModel()))
} else {
// there is no key,then goes to login page
navigator.switchRoot(keyWindow: window!, scene: .intro(viewModel: IntroViewModel()))
}
2.Login Page
by calling Api,you can get a token(key) from api,and this token is highly customizsed by backend developer.please store this token(key) in user default.
3.You will need this token later whenever you need to call some authorised API in your app.
You seem to be missing the initialization for window, which can be fixed like this:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
window = UIWindow(windowScene: windowScene)
window?.makeKeyAndVisible()
if let logId = UserDefaults.standard.value(forKey: "loginId") {
goToPlayerMenu()
}
}

Perform segue in AppDelegate

When a Firebase token is invalid, I want that the user is redirect to my app loginVC. This is my code:
func userErrorLogout() {
print("user error logout")
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewController: ViewController = storyboard.instantiateViewController(withIdentifier: "loginVC") as! ViewController;
let rootViewController = self.window!.rootViewController as! UINavigationController;
rootViewController.pushViewController(viewController, animated: true);
}
I get an error on "let rootViewController:.... = 2019-11-27 13:03:49.364864+0100 Geo[25133:2193886] Fatal error: Unexpectedly found nil while unwrapping an Optional value: file
Since SWIFT is new to me, I am not able to debug this message. How do I perform the redirection?
you need to use the below code :
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewController: ViewController = storyboard.instantiateViewController(withIdentifier: "loginVC") as! ViewController;
let window = (UIApplication.shared.delegate as! AppDelegate).window!
DispatchQueue.main.async {
window.rootViewController = viewController
}
You need to assign the value for your rootViewController. Try this:
func userErrorLogout() {
print("user error logout")
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewController: ViewController = storyboard.instantiateViewController(withIdentifier: "loginVC") as! ViewController;
let nav = UINavigationController(rootViewController: viewController)
self.window?.rootViewController = nav
}
You need to set the viewcontroller to window. You can do like below. This code also has transition animation it gives fade to transition.
// MARK: WINDOW SET
func gotoIntro() {
UIView.transition(with: window!, duration: 0.5, options: .transitionCrossDissolve, animations: {
UIView.performWithoutAnimation({
let introStoryboard = UIStoryboard(name: "Intro", bundle: nil)
let navigationController = introStoryboard.instantiateInitialViewController() as! UINavigationController
self.window?.rootViewController = navigationController
})
}, completion: nil)
}
As of iOS 13, pushing a VC at the start of a launch is not possible from AppDelegate anymore (Not 100% sure).
You must use SceneDelegate if you wish to present the view from your root.
To do so, simply do this inside your SceneDelegate file. I have tested this approach on my own app and is working 100%
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
guard let windowScene = (scene as? UIWindowScene) else { return }
self.window = UIWindow(windowScene: windowScene)
// check if the token is valid
if valid {
let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "yourVC")
self.window?.rootViewController = vc
self.window?.makeKeyAndVisible()
}
else {
// token is invalid
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let rootVC = storyboard.instantiateViewController(identifier: "invalidVC")
let rootNC = UINavigationController(rootViewController: rootVC)
self.window?.rootViewController = rootNC
self.window?.makeKeyAndVisible()
}
}

Present Subview inside a UINavigationController from Keyboard Extension

I have a keyboard extension and want the user to be able to tap on "settings", and be taken to the settings page inside the actual app. I was pretty excited when I got that working, but I realized that the page wasn't inside the navigation controller anymore!
Here is my code. How can I augment it to present a specific sub-screen inside my 'TransparentNavigationController'?
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let urlPath : String = url.path as String!
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if(urlPath == "/inner"){
let innerPage: myStampsVC = mainStoryboard.instantiateViewController(withIdentifier: "myStampsVC") as! myStampsVC
self.window?.rootViewController = innerPage
}
self.window?.makeKeyAndVisible()
return true
}
I've tried different mixes of
let navigationController = window?.rootViewController as! UINavigationController
let innerPage = navigationController.viewControllers[4] as! myStampsVC
but I'm missing something. Thanks for any nudges in the right direction.
Here's the answer:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let urlPath = url.path
if(urlPath == "/inner"){
func showMyStamps(in navigationController: UINavigationController) {
navigationController.popToRootViewController(animated: false)
_ = navigationController.topViewController?.view
let innerViewController = myStampsVC() as UIViewController
navigationController.pushViewController(innerViewController, animated: false)
}
switch window!.rootViewController {
case let demo as DemoScreen:
if let navC = demo.presentedViewController as? UINavigationController {
showMyStamps(in: navC)
} else {
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let navC = storyBoard.instantiateViewController(withIdentifier: "TransparentNavController") as! UINavigationController
demo.present(navC, animated: false)
showMyStamps(in: navC)
}
case let navC as UINavigationController:
showMyStamps(in: navC)
default: assertionFailure()
}
}
return true
}