简体   繁体   中英

Using 3D Touch in my application

So i am trying to add 3D Touch on my application icon using shortCutItems. Here is my 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)
    }
}

I have some issues. FYI! I do not have a tabBarController in my project.

When i open my application using the 3D Touch items, it freezes for 4-5 seconds before it opens the application. When the application is opened, the back buttons does not work.

So is there any possible ways to open the app on the initial controller, and perform segue to the correct 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
}

Please find more impletation details of how to handle quick actions in my QuickActionsManager , or checkout the entire 3DTouch sample of code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM