ios - 在我的应用程序中使用 3D Touch

标签 ios swift 3dtouch uiapplicationshortcutitem

所以我正在尝试使用 shortCutItems 在我的应用程序图标上添加 3D Touch。这是我的 AppDelegate.swift:

import UIKit
import Parse

//MARK: - Handle QuickActions For ShorCut Items -> AppDelegate Extension
@available(iOS 9.0, *)
typealias HandleForShorCutItem = AppDelegate
@available(iOS 9.0, *)
extension HandleForShorCutItem {

    /// Define quick actions type
    enum QuickActionsType: String {
        case JegHarAldri =     "JEGHARALDRI"
        case Pling =   "PLING"
        case FlasketutenPekerPå =    "FLASKETUTENPEKERPÅ"
        case KortetTaler =  "KORTETTALER"
    }
}

@available(iOS 9.0, *)
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

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

        Parse.setApplicationId("XX",
            clientKey: "XX")

        // Register for Push Notitications
        if application.applicationState != UIApplicationState.Background {
            // Track an app open here if we launch with a push, unless
            // "content_available" was used to trigger a background push (introduced in iOS 7).
            // In that case, we skip tracking here to avoid double counting the app-open.

            let preBackgroundPush = !application.respondsToSelector("backgroundRefreshStatus")
            let oldPushHandlerOnly = !self.respondsToSelector("application:didReceiveRemoteNotification:fetchCompletionHandler:")
            var pushPayload = false
            if let options = launchOptions {
                pushPayload = options[UIApplicationLaunchOptionsRemoteNotificationKey] != nil
            }
            if (preBackgroundPush || oldPushHandlerOnly || pushPayload) {
                PFAnalytics.trackAppOpenedWithLaunchOptions(launchOptions)
            }
        }
        if application.respondsToSelector("registerUserNotificationSettings:") {
            if #available(iOS 8.0, *) {
                let types:UIUserNotificationType = ([.Alert, .Sound, .Badge])
                let settings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: types, categories: nil)
                application.registerUserNotificationSettings(settings)
                application.registerForRemoteNotifications()
            } else {
                application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
            }
        }
        else {
            // Register for Push Notifications before iOS 8
            application.registerForRemoteNotificationTypes([.Alert, .Sound, .Badge])
        }

        //// - Add lines before the return true

        let currentInstallation: PFInstallation = PFInstallation.currentInstallation()
        currentInstallation.badge = 0
        currentInstallation.saveEventually()

        //UIApplication.sharedApplication().applicationIconBadgeNumber = 11

        return true
    }

    func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
        let installation = PFInstallation.currentInstallation()
        installation.setDeviceTokenFromData(deviceToken)
        installation.saveInBackground()
    }

    func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
        if error.code == 3010 {
            print("Push notifications are not supported in the iOS Simulator.")
        } else {
            print("application:didFailToRegisterForRemoteNotificationsWithError: %@", error)
        }
    }

    func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
        PFPush.handlePush(userInfo)
        if application.applicationState == UIApplicationState.Inactive {
            PFAnalytics.trackAppOpenedWithRemoteNotificationPayload(userInfo)
        }
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        NSUserDefaults.standardUserDefaults().removeObjectForKey("KortetTalerKey")
        NSUserDefaults.standardUserDefaults().removeObjectForKey("TerningspilletKey")
        NSUserDefaults.standardUserDefaults().removeObjectForKey("segmentKey")
        NSLog("Keys Deleted")
    }





    //MARK: - Handle QuickActions For ShorCut Items -> AppDelegate Extension
    typealias HandleForShorCutItem = AppDelegate

    func handleShortcut( shortcutItem:UIApplicationShortcutItem ) -> Bool {

        // Construct an alert using the details of the shortcut used to open the application.
        let alertController = UIAlertController(title: "Shortcut Handled", message: "\"\(shortcutItem.localizedTitle)\"", preferredStyle: .Alert)
        let okAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
        alertController.addAction(okAction)

        // Display an alert indicating the shortcut selected from the home screen.
        window!.rootViewController?.presentViewController(alertController, animated: true, completion: nil)

        return true

    }

    /// Shortcut Item, also called a Home screen dynamic quick action, specifies a user-initiated action for app.
    func QuickActionsForItem(shortcutItem: UIApplicationShortcutItem) -> Bool {
        // set handled boolean
        var isHandled = false

        // Get the string type from shorcut item
        if let shorchutItemType = QuickActionsType.init(rawValue: shortcutItem.type) {

            // Get root navigation controller + root tab bar controller
            let rootNavigationController = window!.rootViewController as? UINavigationController
            let tabbarController = window!.rootViewController as? UITabBarController
            // if needed pop to root view controller
            rootNavigationController?.popToRootViewControllerAnimated(false)

            // return tabbarcontroller selected
            switch shorchutItemType {
            case .JegHarAldri:
                let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("JEGHARALDRI") as UIViewController
                self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                self.window?.rootViewController = initialViewControlleripad
                self.window?.makeKeyAndVisible()
                isHandled = true
                return true
            case .Pling:
                let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("PLING") as UIViewController
                self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                self.window?.rootViewController = initialViewControlleripad
                self.window?.makeKeyAndVisible()
                isHandled = true
                return true
            case .FlasketutenPekerPå:
                let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("FLASKETUTENPEKERPÅ") as UIViewController
                self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                self.window?.rootViewController = initialViewControlleripad
                self.window?.makeKeyAndVisible()
                isHandled = true
                return true
            case .KortetTaler:
                let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
                let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("KORTETTALER") as UIViewController
                self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
                self.window?.rootViewController = initialViewControlleripad
                self.window?.makeKeyAndVisible()
                isHandled = true
                return true

            }
        }
        return isHandled
    }

    /// Calls - user selects a Home screen quick action for app
    func application(application: UIApplication, performActionForShortcutItem shortcutItem: UIApplicationShortcutItem, completionHandler: (Bool) -> Void) {
        // perform action for shortcut item selected
        let handledShortCutItem = QuickActionsForItem(shortcutItem)
        completionHandler(handledShortCutItem)
    }
}

我有一些问题。供引用!我的项目中没有 tabBarController。

当我使用 3D Touch 项目打开我的应用程序时,它会在打开应用程序之前卡住 4-5 秒。打开应用程序时,后退按钮不起作用。

那么有什么方法可以在初始 Controller 上打开应用程序,并执行转至正确的 View Controller 吗?

最佳答案

 private func showViewController(viewControllerKey: ViewControllerKeys) -> Bool
{
    // Init the storyboard
    let storyboard = UIStoryboard(name: "Main", bundle: nil)

    // Init the root navigationController
    guard let navigationController = storyboard.instantiateInitialViewController() as? UINavigationController else { return false }
    // Set the root navigationController as rootViewController of the application
    UIApplication.sharedApplication().keyWindow?.rootViewController = navigationController

    // Init the wanted viewController
    guard let viewController = storyboard.instantiateViewControllerWithIdentifier(viewControllerKey.rawValue) else { return false }
    // Push this viewController
    navigationController.pushViewController(viewController, animated: false)

    return true
}

请在我的 QuickActionsManager 中找到有关如何处理快速操作的更多实现细节,或检查整个 3DTouch sample of code

关于ios - 在我的应用程序中使用 3D Touch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34571742/

相关文章:

ios - xCode:找不到库 - lPods-Bolts - 退出代码 1

ios - 如何使用存储在 CocoaTouch 框架中的 Localizable.strings?

ios - 由于意外崩溃,3D Touch 快捷方式将无法使用

ios - 3D Touch Quick Action 4 项目限制?

ios - 使用 uitableviewcontroller 时,无论行数如何,如何将按钮添加到屏幕底部?

objective-c - 为什么我的 UIActionSheet 被我的 TabBarController 隐藏了?

ios - CAKeyframeAnimation - 停止无限循环

ios - DispatchQueue.main.async 不调用转义闭包

arrays - 数组的数组快速行为

IOS9。是否可以在应用程序中禁用 3D 触控?