How to check NsUserDefaults from launch screen in IOS? - ios

I am new in iOS application development. In my application I have a launch screen,login page and a home page. The launch screen is in separate storyboard and I want to check NSUserDefaults from launch screen to decide the user already logged in or not or how to check NSUserDefaults to bypass login screen to home screen.

If with launch screen you mean the a storyboard that is displayed while the app is starting then you are out of luck.
Since your app is starting, no code is run and you can not launch anything. You will have to do this is UIApplicationDelegate.

What are you looking for is the application(_:didFinishLaunchingWithOptions:) method in the AppDelegate:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// check whatever, so I can decide which ViewController should be the rootViewController
return true
}

you can access the NSUserDefaults in AppDelegate Class, and also you need to access your ViewController from storyboard to show as home screen.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
if (NSUserDefaults.standardUserDefaults().objectForKey("login") == nil)
{
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "login")
}
if (NSUserDefaults.standardUserDefaults().boolForKey("login") == true)
{
do {
let arr1 = try UserProfileDataHelper.find("1")
if arr1?.Type == "Customer" {
currentUser = "Customer"
screenlaunch("MENU")
}else{
currentUser = "Store"
screenlaunch("HOME")
}
} catch _{}
}
return true
}
func screenlaunch(str : String )
{
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let homeViewController = mainStoryboard.instantiateViewControllerWithIdentifier(str)
let navigationController :UINavigationController = UINavigationController(rootViewController: homeViewController)
navigationController.navigationBarHidden = true
window!.rootViewController = nil
window!.rootViewController = navigationController
window?.makeKeyWindow()
}

Related

view tab bar controller from storyboard swift 5

I am working on swift 5 and xcode 11.5
I am trying to move user from main storyboard to tab bar controller if he is logged in,
in my appDelegate I tried this
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let api_token = helper.getApiToken() {
print("api_token: \(api_token)")
let tab = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(identifier: "maintab")
window?.rootViewController = tab
}
return true
}
here I want to check if there is a user api_token, if yes move to the tab bar
if no show the main storyboard
but it always goes to main.storyboard even if there is a token!
Try this code
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let api_token = helper.getApiToken() {
print("api_token: \(api_token)")
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let tab = storyboard.instantiateViewController(withIdentifier: "maintab")
window?.rootViewController = tab
}
return true
}

iOS state restoration issue with DrawerController

I have an app written in Swift 3.1, using Xcode 8.3.3.
I am currently trying to implement state preservation/restoration.
To do this I have implemented shouldSaveApplicationState and willFinishLaunchingWithOptions methods in AppDelegate.swift and set to return true:
// AppDelegate.swift
// STATE RESTORATION CALLBACKS
func application(_ application: UIApplication, shouldSaveApplicationState coder: NSCoder) -> Bool {
debug_print(this: "shouldSaveApplicationState")
return true
}
func application(_ application: UIApplication, shouldRestoreApplicationState coder: NSCoder) -> Bool {
debug_print(this: "shouldRestoreApplicationState")
restoringState = true
return true
}
func application(application: UIApplication, willFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool {
debug_print(this: "willFinishLaunchingWithOptions")
return true
}
I’ve also provided restoration IDs for all involved viewcontrollers and navigationcontrollers.
I'm using a 3rd party library to handle side drawer navigation container (https://github.com/sascha/DrawerController). The initial viewcontroller is set programmatically inside the didFinishLaunchingWithOptions method, see below.
// AppDelegate.swift
var centerContainer: DrawerController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "RootViewControllerNav") as! UINavigationController
let leftViewController = mainStoryboard.instantiateViewController(withIdentifier: "SideDrawerViewController") as! UITableViewController
centerContainer = DrawerController(centerViewController: centerViewController, leftDrawerViewController: leftViewController)
centerContainer?.restorationIdentifier = "DrawerControllerView"
window = UIWindow(frame: UIScreen.main.bounds)
window?.restorationIdentifier = "MainWindow"
window?.rootViewController = centerContainer
window?.makeKeyAndVisible()
return true
}
When app opens and attempts to restore state, it displays the correct viewcontroller (last controller before app closed) temporarily, then once app becomes active it reverts back to the initial viewcontroller.
For example, the following happens:
Open app Navigate to the “settings” view via the side menu
Navigate to the home screen
Stop running xcode and start it again
App will open showing settings view, then revert back to home view
Can anyone tell me what is causing this, or where I am going wrong? Let me know if you need any more code examples.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let leftSideDrawerViewController = mainStoryboard.instantiateViewController(withIdentifier: "SideDrawerViewController") as! UITableViewController
let centerViewController = mainStoryboard.instantiateViewController(withIdentifier: "RootViewControllerNav") as! UINavigationController
let navigationController = UINavigationController(rootViewController: centerViewController)
navigationController.restorationIdentifier = "navigationControllerKey"
let leftSideNavController = UINavigationController(rootViewController: leftSideDrawerViewController)
leftSideNavController.restorationIdentifier = "LeftNavigationController"
self.drawerController = DrawerController(centerViewController: navigationController, leftDrawerViewController: leftSideNavController, rightDrawerViewController: nil)
self.drawerController.openDrawerGestureModeMask = .all
self.drawerController.closeDrawerGestureModeMask = .all
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = self.drawerController
return true
}

Firebase + Swift: Bypass User Login Screen

So i'm working on a new app and i'm using Firebase to manage all the backend stuff with user logins etc, i've created a login/signup screen for the users when they load the app. What i'm trying to do is load the HomeScreenVC if the user is already logged in and if the user isn't then they would be directed to the login/register vc.
I kind of have it working in the sense that it works if the user is already a currentUser but the issue i'm having is that if the user has never loaded the app then it crashes as it can't detect currentUser.
My code I have in the AppDelegate is:
var window: UIWindow?
var storyboard: UIStoryboard?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
FIRApp.configure()
self.storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
let currentUser = FIRAuth.auth()?.currentUser!
if currentUser != nil
{
self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("tabVC")
}
else
{
self.window?.rootViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginScreen")
}
return true
}
This is the error i get: here
Any help would be great! I'm using the latest version of Firebase and Swift 2.
You are force unwrapping nil on that line, causing the crash. Remove the ! from FIRAuth.auth()?.currentUser!
update for swift 3 and firebase 4.8
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = .lightContent
// Override point for customization after application launch.
// add firebase
FirebaseApp.configure()
// check user status then set initial Viewcontroller
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let startMainVC = storyboard.instantiateViewController(withIdentifier: "MainVC")
let startIntroVC = storyboard.instantiateViewController(withIdentifier: "IntroVC")
// check if user is logged
if authProvider.Instance.userStatus() == true{
self.window?.rootViewController = startMainVC
}
else
{
self.window?.rootViewController = startIntroVC
}
return true
}

How to Pass Values from Separate Classes to AppDelegate?

I have a class in my SignInViewController.swift:
class CredentialState: NSObject {
static let sharedInstance = CredentialState()
var signedIn = false
var displayName: String?
var photoUrl: NSURL?
}
I would like to use the variable signedIn to authenticate users in AppDelegate with an if-else statement. Currently, I have a way to set the viewcontroller to CustomTabBarController (custom programmatically made) or SignInViewController (storyboard made). The if statement would basically say if the value is false set the controller to the sign in screen and if it's true then go to the tab bar screen.
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window?.makeKeyAndVisible()
// Main view controller is inside of customtabbarcontroller, which gives a tab overlay
// window?.rootViewController = CustomTabBarController()
// Sets the main view to a storyboard element, such as SignInVC
let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
let loginVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInViewController
self.window?.rootViewController = loginVC
return true
}
if i understood you correctly:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
FIRApp.configure()
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.mainScreen().bounds)
// check login state
if CredentialState.sharedInstance.signedIn {
// Main view controller is inside of customtabbarcontroller, which gives a tab overlay
window?.rootViewController = CustomTabBarController()
} else {
// Sets the main view to a storyboard element, such as SignInVC
let storyboard = UIStoryboard(name: "SignIn", bundle: nil)
let loginVC = storyboard.instantiateViewControllerWithIdentifier("SignInVC") as! SignInViewController
window?.rootViewController = loginVC
}
window?.makeKeyAndVisible()
return true
}
I am not so sure of what you are asking, yet I'll try to answer that. Basically what you need to do is just simply have this piece of code above your CredentialState class:
credentialState : CredentialState = CredentialState()
In this way you can change or check your signedIn variable from AppDelegate. So simply in the AppDelegate file you can:
if(credentialState.signedIn == true) ...
Hope I was able to answer your question

performSegue before the View is visible

I have two views
ViewController-> Main view
LoginVC -> LogIn View
My initial view is ViewController which contains buttons and some text.
What i want to achive
Perform a segue that will transfer the view to Login if the user is not yet log in.
What i have done
Inside my ViewController I did a check if USER_ID is nil then if its a nil then i will perform a segue.
override func viewWillAppear(animated: Bool) {
if Globals.USER_ID == nil{
self.performSegueWithIdentifier("goto_login", sender: nil)
// dispatch_async(dispatch_get_main_queue(), {
// self.performSegueWithIdentifier("goto_login", sender: nil)
// })
}
}
What is my problem
My Problem is whether I use viewWillAppear or viewDidLoad or viewDidAppear to transfer view from ViewController to LoginVC.ViewController will be visible in a single second before the the login screen appears and i want to get rid of it.Can someone help me solve this issue.
I have same functionality in my App. I achieved it by checking for userID in AppDelegate.swift inside function func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
So, delete the segue and your modified code will look like as follows:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
if Globals.USER_ID == nil{
let loginScreen = storyBoard.instantiateViewControllerWithIdentifier("LoginVC")
self.window?.rootViewController = loginScreen
}else{
let mainScreen = storyBoard.instantiateViewControllerWithIdentifier("ViewController")
self.window?.rootViewController = mainScreen
}
return true
}
This way you will not need any of the method like viewDidLoad(), viewDidAppear() or viewWillAppear()to be used for this purpose.
Just as an addition to this answer - Use the instance of AppDelegate again after logout happens. For example you should do following in logout method:
func logout() {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
Globals.USER_ID = nil
appDelegate.window?.rootViewController = loginScreen
}
}
This way you can clear the userID and navigate back to login screen after the user logouts.

Resources