简体   繁体   中英

Swift App Crashing after moving to view controller from AppDelegate

I am using moving to a new view controller from app delegate using this code I found from somewhere on stack overflow

    func changeRootViewController(with identifier:String!) {
    let storyboard = self.window?.rootViewController?.storyboard
    let desiredViewController = storyboard?.instantiateViewController(withIdentifier: identifier);

    let snapshot:UIView = (self.window?.snapshotView(afterScreenUpdates: true))!
    desiredViewController?.view.addSubview(snapshot);

    self.window?.rootViewController = desiredViewController;

    UIView.animate(withDuration: 0.3, animations: {() in
        snapshot.layer.opacity = 0;
        snapshot.layer.transform = CATransform3DMakeScale(1.5, 1.5, 1.5);
    }, completion: {
        (value: Bool) in
        snapshot.removeFromSuperview();
    });
}

It works fine and I am able to move to a new view controller with the animation ( WHICH IS REQUIRED ). But as soon as I move to some other app and return back, the app crashes with error.

Cannot snapshot view (; layer = >) with afterScreenUpdates:NO, because the view is not in a window. Use afterScreenUpdates:YES. fatal error: unexpectedly found nil while unwrapping an Optional value

The other code I have for opening a view controller from AppDelegate

func showViewController(id: String){
    let mainStoryboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewControlleripad : UIViewController = mainStoryboard.instantiateViewController(withIdentifier: id) as UIViewController
    self.window = UIWindow(frame: UIScreen.main.bounds)
    self.window?.rootViewController = initialViewControlleripad
    self.window?.makeKeyAndVisible()
}

It works perfectly but when tried to add animation the animation doesn't work. So kindly help in resolving these issues.

Have you tried with animation like ?

UIView.transition(with: appDel.window!,
              duration: 0.25,
               options: .transitionCrossDissolve,
            animations: { appDel.window?.rootViewController = vc } ,
            completion: nil)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM