0

I would like to create a 3D Touch ShortCut on my app, I've done everything about the shortcut it self, it appear correctly, with text and icon.

When I run this shortcut, my app crashes, because the function in AppDelegate.swift calls a function inside my root viewController that instantiate AVPlayer(), make it play and finally, updates the user interface by changing the image of my play/stop button and there is where I have my problem.

I give you the code bellow.

here is a part of my AppDelegate.swift:

func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    if shortcutItem.type == "fr.xxxxxxxxxxx.xxxxxxxxxxxxxx.playRadio" {
        let playerVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier:"Player") as! ViewController
        playerVC.playPlayer()
    }
}

and here is a part of my ViewController.swift:

@objc func playPlayer() {
    initAVAudioSession()
    setupPlayer()
    RadioPlayer.rate = 1.0
    RadioPlayer.play()
    playButton.setImage(UIImage(named: "stopbutton"), for: .normal)
}

It crashes at playButton line with this error :

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

Note: If I insert a question mark (?) on my playButton inside playPlayer() (like so playButton?.setImage(...)), everything works well, but my UI is not updated. My rootViewController is a UITabBarController placed before Player:ViewController

How to make this working correctly?

Did'
  • 171
  • 11
  • you don't present viewcontroller... – Tomasz Czyżak Nov 12 '17 at 10:13
  • @TomaszCzyżak, I didn't specify that my rootViewController is a UITabBarController placed before my ViewController. – Did' Nov 12 '17 at 17:35
  • So you have created new viewcontroller instead reaching to the one already created by application. see: https://developer.apple.com/documentation/uikit/uitabbarcontroller/1621172-selectedviewcontroller – Tomasz Czyżak Nov 13 '17 at 07:24

1 Answers1

0

I found the solution due to this post this post

 func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        if shortcutItem.type == "fr.xxxxxxxxxx.xxxxxxxxxxxx.playRadio" {
            //window!.rootViewController?.present("Player", animated: true, completion: nil)
            //selectedViewController .playPlayer()
            if let rootViewController = window?.rootViewController as? UITabBarController {
                if let viewController = rootViewController.viewControllers?.first as? ViewController {
                    viewController.playPlayer()
                }
            }
        }
    }
Did'
  • 171
  • 11