Perform Segue from App Delegate Swift

Perform Segue from App Delegate swift

c_rath's answer is mostly right, but you don't need to make the view controller a root view controller. You can in fact trigger a segue between the top view on the navigation stack and any other view controller, even from the App Delegate. For example, to push a storyboard view controller, you could do this:

Swift 3.0 and Later

// Access the storyboard and fetch an instance of the view controller
let storyboard = UIStoryboard(name: "Main", bundle: nil);
let viewController: MainViewController = storyboard.instantiateViewController(withIdentifier: "ViewController") as! MainViewController;

// Then push that view controller onto the navigation stack
let rootViewController = self.window!.rootViewController as! UINavigationController;
rootViewController.pushViewController(viewController, animated: true);

Swift 2.0 and Earlier

// Access the storyboard and fetch an instance of the view controller
var storyboard = UIStoryboard(name: "Main", bundle: nil)
var viewController: MainViewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as MainViewController

// Then push that view controller onto the navigation stack
var rootViewController = self.window!.rootViewController as UINavigationController
rootViewController.pushViewController(viewController, animated: true)

Perform Segue from App Delegate - Swift

First, go in your storyboard and set a storyboard ID to your viewController.
Storyboard ID
Next, go in your viewController and add this methods in your class.

import UIKit

class ViewController2: UIViewController {

// Change the name of the storyboard if this is not "Main"
// identifier is the Storyboard ID that you put juste before
class func instantiate() -> ViewController2 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "\(ViewController2.self)") as! ViewController2

return viewController
}

}

Then, in your app delegate, when you want to show the viewController do

window?.rootViewController = ViewController2.instantiate()

Perform segue from AppDelegate

func showLoginScreen(){
let loginVC = UIStoryboard.getMainStoryboard().instantiateViewController(withIdentifier: "LoginViewControllerIdentifier") as! LoginViewController

UIApplication.shared.delegate!.window!!.rootViewController = loginVC
}

extension UIStoryboard{
//returns storyboard from default bundle if bundle paased as nil.
public class func getMainStoryboard() -> UIStoryboard{
return UIStoryboard(name: "Main", bundle: nil)
}
}

i want to perform a segue from the App delegate in the google sign in method

The solution is actually pretty simple and was staring me in the face the whole time

I implemented multiple segues from my initial ViewController. I then took off the email's characters that came before the domain name. Then based on the domain name I performed a certain segue.

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, GIDSignInDelegate{

let userDefault  = UserDefaults()

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

}else{
let userId = user.userID // For client-side use only!
let idToken = user.authentication.idToken // Safe to send to the server
let fullName = user.profile.name
let givenName = user.profile.givenName
let familyName = user.profile.familyName
let email = user.profile.email
let str = email
let me = str?.count
let int = (me!-9)
let NewStr = str?.dropFirst(int)
print(NewStr)

guard let authentication = user.authentication else{return}
let crendential = GoogleAuthProvider.credential(withIDToken: authentication.idToken, accessToken: authentication.accessToken)
Auth.auth().signInAndRetrieveData(with: crendential) {(result, error)in
if error == nil {
self.userDefault.set(true, forKey: "usersignedIn")
self.userDefault.synchronize()
if(NewStr == "gmail.com"){

self.window?.rootViewController?.performSegue(withIdentifier: "Megue", sender: self)
}
}else {
self.window?.rootViewController?.performSegue(withIdentifier: "Wegue", sender: self)
print(error?.localizedDescription ?? "me")
}
}

}

}

var window: UIWindow?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.

FirebaseApp.configure()
// Use Firebase library to configure APIs

GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID
GIDSignIn.sharedInstance().delegate = self
return true
}

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication:options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: [:])
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}

func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}

func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

}
extension String {

var length: Int {
return count
}

subscript (i: Int) -> String {
return self[i ..< i + 1]
}

func substring(fromIndex: Int) -> String {
return self[min(fromIndex, length) ..< length]
}

func substring(toIndex: Int) -> String {
return self[0 ..< max(0, toIndex)]
}

subscript (r: Range<Int>) -> String {
let range = Range(uncheckedBounds: (lower: max(0, min(length, r.lowerBound)),
upper: min(length, max(0, r.upperBound))))
let start = index(startIndex, offsetBy: range.lowerBound)
let end = index(start, offsetBy: range.upperBound - range.lowerBound)
return String(self[start ..< end])
}

}

Perform Segue from App Delegate - Swift

First, go in your storyboard and set a storyboard ID to your viewController.
Storyboard ID
Next, go in your viewController and add this methods in your class.

import UIKit

class ViewController2: UIViewController {

// Change the name of the storyboard if this is not "Main"
// identifier is the Storyboard ID that you put juste before
class func instantiate() -> ViewController2 {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "\(ViewController2.self)") as! ViewController2

return viewController
}

}

Then, in your app delegate, when you want to show the viewController do

window?.rootViewController = ViewController2.instantiate()


Related Topics



Leave a reply



Submit