如何在应用程序关闭时使用动态快速操作[swift]

问题描述 投票:0回答:2

如何在swift中使用动态快速动作? 如果应用程序处于多任务处理状态,我可以触发我的方法。但如果应用程序没有在后台运行,它就无法工作。 我正在 applicationWillResignActive / sceneWillResignActive 中设置快速操作。 我正在处理我的方法: “func application(_ application:UIApplication,performActionFor快捷方式项目:UIApplicationShortcutItem,completionHandler:@escaping(Bool)-> Void)” 和
“func windowScene(_ windowScene:UIWindowScene,performActionFor快捷方式项目:UIApplicationShortcutItem,completionHandler:@escaping(Bool)-> Void)”

有什么建议吗?

swift dynamic shortcut
2个回答
2
投票

performActionFor 方法仅在应用程序运行时(在后台)被调用。如果不是,则需要在应用程序启动时在 didFinishLaunchingWithOptions 或 willFinishLaunchingWithOptions 中检查快捷方式。快捷方式项将在启动项中。

类似这样的:

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

    if let shotcutItem = launchOptions?[UIApplication.LaunchOptionsKey.shortcutItem] as? UIApplicationShortcutItem{
        handleShortcutItem(shortcutItem)
    }

    return true
}

显然

handleShortcutItem
是一种实际处理快捷方式并执行您想要的操作的方法。您应该能够对这两种情况使用同一个。


1
投票

对于场景委托,您可以使用以下代码:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
   //check if there tapped shortcut item when app was closed
   if let shortcutItem = connectionOptions.shortcutItem {
      //do something with shortcutItem
   }
}
© www.soinside.com 2019 - 2024. All rights reserved.