Сделай что-нибудь с Quick Action - PullRequest
0 голосов
/ 21 октября 2019

Извините, если это глупый вопрос, Настройка быстрого действия 3D Touch. Я поместил все в файл .plist, и мне пришлось поместить это в мой файл AppDelegate.swift

AppDelegate.swift

func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
    // Called when a new scene session is being created.
    // Use this method to select a configuration to create the new scene with.

    // Grab a reference to the shortcutItem to use in the scene
    if let shortcutItem = options.shortcutItem {
        shortcutItemToProcess = shortcutItem
    }

    // Previously this method only contained the line below, where the scene is configured
    return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role) }

, и это в мой SceneDelegate.swift

// Shortcut code
    func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
        // When the user opens the app through a quick action, this is now the method that will be called
        (UIApplication.shared.delegate as! AppDelegate).shortcutItemToProcess = shortcutItem

    }
    // Shortcut code
    func sceneDidBecomeActive(_ scene: UIScene) {
        // Is there a shortcut item that has not yet been processed?
        if let shortcutItem = (UIApplication.shared.delegate as! AppDelegate).shortcutItemToProcess {


            if shortcutItem.type == "com.application.Start" {
                print("Start Shortcut pressed")

                //let vc = ViewController ()
                //vc.startAct()

            }
            // Reset the shorcut item so it's never processed twice.
            (UIApplication.shared.delegate as! AppDelegate).shortcutItemToProcess = nil
        }
    }

Я хочу запустить функцию startAct() { ... }, которая находится в главном файле приложения с именем ViewController.swift

Я пытался

let vc = ViewController ()
vc.startAct()

, и она вроде запускается, но сразу падаетпрочь в первой строке с ошибкой об развёртывании нулевого значения или чего-то ещё. Я предполагаю, что он на самом деле не загружает основной вид, но пытается запустить его из SceneDelegate.swift, что не может быть правильным.

Заранее спасибо.

1 Ответ

0 голосов
/ 22 октября 2019

Это, кажется, вызывает некоторую путаницу, поэтому я покажу, что я делаю.

Вы должны реализовать свой ответ на элемент ярлыка в двух местах: в willConnectTo делегата сцены и в performActionFor. Чтобы помочь вам в тестировании, я просто удалю все свои проверки и анализ ошибок и просто продемонстрирую, что мы на самом деле реагируем на элемент ярлыка:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    if let shortcutItem = connectionOptions.shortcutItem {
        let alert = UIAlertController(title: "Hello", message: "", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default))
        self.window?.makeKeyAndVisible()
        self.window?.rootViewController?.present(alert, animated: true)
    }
}

func windowScene(_ windowScene: UIWindowScene, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
    let alert = UIAlertController(title: "Hello", message: "", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default))
    self.window?.rootViewController?.present(alert, animated: true)
    completionHandler(true)
}

, который показывает предупреждение о том, приостановлено ли приложение или завершенозаранее.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...