【问题标题】:PerformActionFor shortcutItem AppDelegate.swift (Swift 4)PerformActionForshortcutItem AppDelegate.swift (Swift 4)
【发布时间】:2017-11-12 10:04:30
【问题描述】:

我想在我的应用程序上创建一个 3D Touch ShortCut,我已经完成了所有关于它自己的快捷方式,它显示正确,带有文本和图标。

当我运行这个快捷方式时,我的应用程序崩溃了,因为 AppDelegate.swift 中的函数调用了我的根 viewController 中的一个函数,该函数实例化了 AVPlayer(),让它开始播放,最后通过更改我的播放图像来更新用户界面/stop 按钮,这就是我的问题所在。

我给你下面的代码。

这是我的 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()
    }
}

这是我的 ViewController.swift 的一部分:

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

它在playButton 行崩溃并出现此错误:

线程 1:致命错误:打开包装时意外发现 nil 可选值

注意:如果我在 playButton 内的 playPlayer() 上插入问号 (?)(就像 playButton?.setImage(...) 一样),一切正常,但我的 UI 没有更新。 我的 rootViewController 是放置在 Player:ViewController 之前的 UITabBarController

如何使它正常工作?

【问题讨论】:

  • 你没有展示viewcontroller...
  • @TomaszCzyżak,我没有指定我的 rootViewController 是放置在我的 ViewController 之前的 UITabBarController。
  • 所以您创建了新的视图控制器,而不是访问应用程序已经创建的视图控制器。见:developer.apple.com/documentation/uikit/uitabbarcontroller/…

标签: swift appdelegate 3dtouch uiapplicationshortcutitem


【解决方案1】:

由于这篇帖子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()
                }
            }
        }
    }

【讨论】:

    猜你喜欢
    • 2020-07-10
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    相关资源
    最近更新 更多