keep user logged in ios app swift - ios

I have made app which include login and signup functionality. When I run my app at that time login and other functionality everything is going ok but when I stop my app and run it again login page showing again can I make user logged in when again app launch. Below is my code which I have used in my app.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
let prefs:NSUserDefaults = NSUserDefaults.standardUserDefaults()
let isLoggedIn:Int = prefs.integerForKey("ISLOGGEDIN") as Int
if (isLoggedIn != 1) {
self.performSegueWithIdentifier("goto_login", sender: self)
} else {
self.usernameLabel.text = prefs.valueForKey("USERNAME") as? String
}
}
import UIKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
/*
var rootViewController = self.window!.rootViewController
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main" , bundle: nil)
var isUserLoggedIn:Bool = NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn")
if(!isUserLoggedIn){
var loginViewController = mainStoryboard.instantiateViewControllerWithIdentifier("loginview") as! LoginViewController
window!.rootViewController = loginViewController
window!.makeKeyAndVisible()
}else{
var protectedPage = mainStoryboard.instantiateViewControllerWithIdentifier("profail") as! ProfailViewController
window!.rootViewController = protectedPage
window!.makeKeyAndVisible()
}
*/
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return true
}
}

Within AppDelegate:-
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let userLoginStatus = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
if(userLoginStatus)
{
let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
.
.
}
Within LoginViewController(Where you have placed business logic for login validation):-
UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()
Within OtherViewController(Where IBAction for Logout is kept):-
UserDefaults.standard.set(false, forKey: "isUserLoggedIn")
UserDefaults.standard.synchronize()

In "didFinishLaunchingWithOptions" method check for user already logged in or not, if yes that set the ProfailViewController to window rootViewController
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
let isUserLoggedIn:Bool = NSUserDefaults.standardUserDefaults().boolForKey("isUserLoggedIn")
if(isUserLoggedIn) {
let mainStoryboard = UIStoryboard(name: "Main" , bundle: nil)
let protectedPage = mainStoryboard.instantiateViewControllerWithIdentifier("profail") as! ProfailViewController
window!.rootViewController = protectedPage
window!.makeKeyAndVisible()
}
return true
}

Related

How to call a view controller via Quick Actions (3D touch) Swift

I'm trying to implement a 3D touch command where if the user presses "New scan", then the view controller ProcessedImageViewController is called. I have already set up the Info.plist to create the quick option, but I am having trouble actually calling the ProcessedImageViewController when "New scan" is pressed.
Here is my code from the AppDelegate.swift:
var launchedShortcutItem: UIApplicationShortcutItem?
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if let shortcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem{
launchedShortcutItem = shortcutItem
}
return true
}
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: #escaping (Bool) -> Void) {
completionHandler(handleShortcutItem(item: shortcutItem))
}
func applicationDidBecomeActive(_ application: UIApplication) {
guard let shortcutItem = launchedShortcutItem else { return }
//If there is any shortcutItem,that will be handled upon the app becomes active
_ = handleShortcutItem(item: shortcutItem)
//We make it nil after perfom/handle method call for that shortcutItem action
launchedShortcutItem = nil
}
func handleShortcutItem(item: UIApplicationShortcutItem) -> Bool {
var handled = false
// Verify that the provided shortcutItem's type is one handled by the application.
let mainStoryboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
var reqVC: UIViewController!
reqVC = mainStoryboard.instantiateViewController(withIdentifier: "ProcessedImageViewController") as! ProcessedImageViewController
handled = true
if let homeVC = self.window?.rootViewController as? UINavigationController {
homeVC.pushViewController(reqVC, animated: true)
} else {
return false
}
return handled
}
When I try to click on "New scan" in the Quick Actions menu, I only get taken to the Root View controller (not ProcessedImageViewController).

Unable to read deeplink URL in AppDelegate method (swift 4, iOS 13)

I'm trying deeplink to open particular page in app on click of shared link from other app/from safari, URL opens the app but unable to take application on particular page i,e, unable to read link (custom URL). This is my custom URL :- WOT://tradeDetail
If anyone knows where i'm going wrong, please help
here is screenshot and code
var window: UIWindow?
var scheme = "WOT"
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
ApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions)
GMSPlacesClient.provideAPIKey(WOT.googlePlaceAPIKey)
if let url = launchOptions?[.url] as? URL {
return handle(url: url)
}
return true
}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return handle(url: url)
}
func handle(url: URL) -> Bool {
switch url.absoluteString {
case "\(scheme)://tradeDetail" : do {
let sb = UIStoryboard(name: "Main", bundle: .main)
let detailView = sb.instantiateViewController(withIdentifier: "SearchedPlaceDetailVC") as? SearchedPlaceDetailVC
window?.rootViewController = detailView
window?.makeKeyAndVisible()
}
default: return false
}
return true
}
You need to call below function to navigate particular page
func application(_ application: UIApplication, continue userActivity:
NSUserActivity, restorationHandler: #escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
let myUrl: String? = userActivity.webpageURL?.absoluteString
if myUrl?.range(of: "tradeDetail") != nil {
let storyboard = UIStoryboard(name: "Main", bundle: Bundle.main)
let yourViewController = storyboard.instantiateViewController(withIdentifier: “YourViewController”) as? YourViewController
self.window?.rootViewController = yourViewController
self.window?.makeKeyAndVisible()
}
return true
}

How to Navigate another page when application launch first time in swift 3

I am implementing an iOS app. when User Launch the application first time, I need to navigate to another page and from next time onwards I need to navigate Home Page. How to do this task in iOS swift?
Updated: if you get this error: "Value of type 'AppDelegate' has no member 'window' ".
Answer is : you have to write your codes inside of SceneDelegate.swift
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
let defaults = UserDefaults.standard
guard let a=UserDefaults.standard.object(forKey: "wantOverview") else {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let initialVc = storyBoard.instantiateViewController(withIdentifier: "firstTimeViewController") as! firstTimeViewController
self.window?.rootViewController = initialVc
self.window?.makeKeyAndVisible()
defaults.set(false, forKey: "wantOverview")
return
}
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let initialVc = storyBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
self.window?.rootViewController = initialVc
self.window?.makeKeyAndVisible()
guard let _ = (scene as? UIWindowScene) else { return }
}
The following solution to this common problem assumes that
At the outset — in this example, that's before the "username" key has been set in the user defaults — we want to launch to the storyboard's Initial View Controller (where the user is supposed to set the "username" key).
Thereafter, we always want to launch to a different view controller in the storyboard, whose identifier in this example is "root".
It's very short and simple!
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if let rvc = self.window?.rootViewController {
if UserDefaults.standard.object(forKey:"username") as? String != nil {
self.window!.rootViewController = rvc.storyboard!.instantiateViewControllerWithIdentifier("root")
}
}
return true
}
}
This can be achieved using userdefaults. Just make a new controller like SplashViewController which will only redirect to desired ViewController.
import UIKit
class SplashViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
decideWhichScreenToShow()
}
// This logic will do
func decideWhichScreenToShow(){
if !UserDefaults.standard.bool(forKey: "your_key"){
// This will execute first time, in that controller's viewDidLoad() make this true
}else{
}
}
}
You can write same logic in Appdelegate.
Create func for checking that if your key in UserDefaults or not using this link & Then check by if...else
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
if isKeyPresentInUserDefaults(key: "isFirstTime") {
let home = HomeVC()
window?.rootViewController = home
} else {
let login = LoginVC()
window?.rootViewController = login
UserDefaults.standard.set(true, forKey: "isFirstTime")
}
return true
}
func isKeyPresentInUserDefaults(key: String) -> Bool {
return UserDefaults.standard.object(forKey: key) != nil
}
Try this:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if firstTime = UserDefaults.standard.object(forKey: "firstTime")
{
let storyboard = UIStoryboard(name: "SecondStoryBoard", bundle: nil)
let MainView = storyboard.instantiateViewController(withIdentifier: "SecondTimeViewController") as! SecondTimeViewController
let navController = UINavigationController.init(rootViewController: MainView)
self.window?.rootViewController = navController
}
else
{
UserDefaults.standard.set(true, forKey: "firstTime")
let storyboard = UIStoryboard(name: "FirstStoryBoard", bundle: nil)
let MainView = storyboard.instantiateViewController(withIdentifier: "FirstTimeViewController") as! FirstTimeViewController
let navController = UINavigationController.init(rootViewController: MainView)
self.window?.rootViewController = navController
}
}
You may use change the didFinishLaunchingWithOptions method in AppDelegate to achieve this.
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
guard let firstTime = UserDefaults.standard.object(forKey: "IsFirstTime") else {
UserDefaults.standard.set(true, forKey: "IsFirstTime")
let storyBoard = UIStoryboard.init(name: "FirstStoryBoard", bundle: nil)
let initialVc = storyBoard.instantiateViewController(withIdentifier: "FirstControllerId") as! FirstTimeViewController
self.window?.rootViewController = initialVc
self.window?.makeKeyAndVisible()
return true
}
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let initialVc = storyBoard.instantiateViewController(withIdentifier: "NormalInitialController") as! ViewController
self.window?.rootViewController = initialVc
self.window?.makeKeyAndVisible()
return true
}
You check if the value for key, "IsFirstTime", exists in UserDefaults. There won't be a value if the app is launching for the first time.
In this case, you can launch your FirstTimeViewController and set a value to the key in UserDefaults.
If a value exists in UserDefaults, just initiate your normal ViewController.

How use AppNavigationController and AppNavigationDrawerController in the same view

I want to use AppNavigationController and AppNavigationDrawerController in the same view, but it is not seen correctly. Thanks
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
let leftViewController = LeftViewController()
let root = PatientListController()
let appToolbarController = AppToolbarController(rootViewController: root)
let appNavigationController = AppNavigationController(rootViewController: appToolbarController)
let appNavDrawerController = AppNavigationDrawerController(rootViewController: appNavigationController, leftViewController: leftViewController)
window = UIWindow(frame: UIScreen.main.bounds)
window!.rootViewController = appNavDrawerController
window!.makeKeyAndVisible()
return true
}
Result
For now I'm using NavigationDrawerController with ToolbarController in the same page. I did my AppDelegate.swift file something like this.
import UIKit
import Material
extension UIStoryboard {
class func viewController(identifier: String) -> UIViewController {
return UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: identifier)
}
}
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
Override point for customization after application launch.
let appToolbarController = AppToolbarController(rootViewController: DashboardVC())
let leftNavigationVC = LeftNavigationVC()
window = UIWindow(frame: Screen.bounds)
window!.rootViewController = AppNavigationDrawerController(rootViewController: appToolbarController, leftViewController: leftNavigationVC, rightViewController: nil)
window!.makeKeyAndVisible()
return true
}
}
BTW, I'm using Swift 3.

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
}

Resources