簡體   English   中英

Obj-C中的3D Touch Home快捷鍵

[英]3D Touch Home Shortcuts In Obj-C

我的所有應用程序目前都是用Obj-C編寫的。 有關使用3D Touch實現主屏幕快捷方式的示例代碼的鏈接https://developer.apple.com/library/content/samplecode/ApplicationShortcuts/Introduction/Intro.html#//apple_ref/doc/uid/TP40016545已完全編譯在斯威夫特。 任何人都會遇到Obj-C的文檔,所以我不需要通過我的AppDelegate進行翻譯了嗎?

更新:

添加Info.plist中的所有快捷方式后,我在AppDelegate.m中添加了:

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler {
    UINavigationController *nav = (UINavigationController *) self.tabBarController.selectedViewController;

    NSLog(@"%@", shortcutItem.type);
    if ([shortcutItem.type isEqualToString:@"com.316apps.iPrayed.addPrayerRequest"]) {
        Requests *gonow = [[Requests alloc] init];

        [nav pushViewController:gonow animated:YES];

    }
    if ([shortcutItem.type isEqualToString:@"com.316apps.iPrayed.addPrayer"]) {

      PrayerStats *controller = [[PrayerStats alloc] init];
        [nav pushViewController:controller animated:YES];

    }

    if ([shortcutItem.type isEqualToString:@"com.316apps.iPrayed.addFast"]) {

      FastStats *controller1 = [[FastStats alloc] init];
        [nav pushViewController:controller1 animated:YES];

    }

    if ([shortcutItem.type isEqualToString:@"com.316apps.iPrayed.addStudy"]) {

      StudyStats *controller2 = [[StudyStats alloc] init];
        [nav pushViewController:controller2 animated:YES];

    }
   }

這允許它工作,而不需要添加任何其他方法,或者向didFinishLaunchingWithOptions添加任何內容。

用戶可以通過快速操作打開應用程序的狀態有兩種。

TL; DR無論應用程序在快速操作完成時的狀態如何,您始終都在做同樣的事情,這就是為什么您只需要覆蓋application:performActionForShortcutItem:completionHandler:所以如果你想做不同的事情,那么你我想在兩個地方處理它們,如果不是那么只是被覆蓋就足夠了。

  • 一個是如果應用程序被殺死或未在后台運行,我們在啟動時獲取快捷方式信息。

  • 另一個是如果應用程序在后台運行,我們會在新的app delegate方法中獲取快捷方式信息。

要在后台處理這些快速操作快捷方式,您需要在App Delegate上覆蓋此方法:

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler

而不是在你的背景中運行(殺死)

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

要么

-(BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions

您應該檢查應用程序是否由快速操作啟動:

UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKey:UIApplicationLaunchOptionsShortcutItemKey];

(鏈接到相關的Apple文檔)來自Apple官方文檔的引用

您有責任確保系統有條件地調用此方法,具體取決於您的某個應用啟動方法(應用程序:willFinishLaunchingWithOptions:或application:didFinishLaunchingWithOptions :)是否已處理快速操作調用。 當用戶為您的應用選擇快速操作並且您的應用啟動而不是激活時,系統會調用啟動方法(在調用此方法之前)。

請求的快速操作可能會使用與應用程序啟動時使用的代碼路徑不同的代碼路徑。 例如,假設您的應用通常會啟動以顯示視圖A,但您的應用是為響應需要視圖B的快速操作而啟動的。要處理此類情況,請在啟動時檢查您的應用是否通過快速操作啟動。 通過檢查UIApplicationLaunchOptionsShortcutItemKey啟動選項密鑰,在您的應用程序中執行此檢查:willFinishLaunchingWithOptions:或application:didFinishLaunchingWithOptions:方法。 UIApplicationShortcutItem對象可用作啟動選項鍵的值。

如果您發現您的應用確實是使用快速操作啟動的,請在啟動方法中執行請求的快速操作,並從該方法返回NO值。 當您返回值NO時,系統不會調用應用程序:performActionForShortcutItem:completionHandler:方法。

如果你查看為apple提供的示例代碼,你會看到他們建議你編寫一個處理你的快捷項的方法,這樣你就可以在所有三個地方處理它:

  • application: performActionForShortcutItem
  • application: didFinishLaunchingWithOptions
  • willFinishLaunchingWithOptions

我做的一個例子是:

- (BOOL)handleShortCutItem:(UIApplicationShortcutItem *)shortcutItem {
    BOOL handled = NO;

    if (shortcutItem == nil) {
        return handled;
    }

    if ([shortcutItem.type isEqualToString:kFavoritesQuickAction]) {
        handled = YES;
    } 

    if (handled) {
        // do action here
    }

    return handled;
}

然后,您只需在獲得快捷項目的任何地方調用此方法。 這應該會幫助你一路走來!

實施以下3個簡單步驟:

步驟1:AppDelegate類中編寫以下方法以配置動態快捷方式項。

注意:如果要將其設置為靜態,可以在info.plist中配置快捷項。 (請參閱Apple文檔。

/**
 *  @brief config dynamic shortcutItems
 *  @discussion after first launch, users can see dynamic shortcutItems
 */
- (void)configDynamicShortcutItems {
    // config image shortcut items
    // if you want to use custom image in app bundles, use iconWithTemplateImageName method
    UIApplicationShortcutIcon *shortcutSearchIcon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeSearch];
    UIApplicationShortcutIcon *shortcutFavoriteIcon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeFavorite];

    UIApplicationShortcutItem *shortcutSearch = [[UIApplicationShortcutItem alloc]
                                                 initWithType:@"com.sarangbang.QuickAction.Search"
                                                 localizedTitle:@"Search"
                                                 localizedSubtitle:nil
                                                 icon:shortcutSearchIcon
                                                 userInfo:nil];

    UIApplicationShortcutItem *shortcutFavorite = [[UIApplicationShortcutItem alloc]
                                                 initWithType:@"com.sarangbang.QuickAction.Favorite"
                                                 localizedTitle:@"Favorite"
                                                 localizedSubtitle:nil
                                                 icon:shortcutFavoriteIcon
                                                 userInfo:nil];


    // add all items to an array
    NSArray *items = @[shortcutSearch, shortcutFavorite];

    // add the array to our app
    [UIApplication sharedApplication].shortcutItems = items;
}

第2步:AppDelegateapplication didFinishLaunchingWithOptions方法編寫下面的代碼。

    // UIApplicationShortcutItem is available in iOS 9 or later.
        if([[UIApplicationShortcutItem class] respondsToSelector:@selector(new)]){

            [self configDynamicShortcutItems];

            // If a shortcut was launched, display its information and take the appropriate action
            UIApplicationShortcutItem *shortcutItem = [launchOptions objectForKeyedSubscript:UIApplicationLaunchOptionsShortcutItemKey];

            if(shortcutItem)
            {
                // When the app launch at first time, this block can not called.
                //App launch process with quick actions
                [self handleShortCutItem:shortcutItem];
            }else{
                // normal app launch process without quick action
            }

        }

第3步:AppDelegate類中編寫下面的委托方法和完成處理程序。

/*
 Called when the user activates your application by selecting a shortcut on the home screen, except when
 application(_:,willFinishLaunchingWithOptions:) or application(_:didFinishLaunchingWithOptions) returns `false`.
 You should handle the shortcut in those callbacks and return `false` if possible. In that case, this
 callback is used if your application is already launched in the background.
 */

- (void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{

    BOOL handledShortCutItem = [self handleShortCutItem:shortcutItem];

    completionHandler(handledShortCutItem);
}


/**
 *  @brief handle shortcut item depend on its type
 *
 *  @param shortcutItem shortcutItem  selected shortcut item with quick action.
 *
 *  @return return BOOL description
 */
- (BOOL)handleShortCutItem : (UIApplicationShortcutItem *)shortcutItem{

    BOOL handled = NO;

    NSString *bundleId = [NSBundle mainBundle].bundleIdentifier;

    NSString *shortcutSearch = [NSString stringWithFormat:@"%@.Search", bundleId];
    NSString *shortcutFavorite = [NSString stringWithFormat:@"%@.Favorite", bundleId];

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];


    if ([shortcutItem.type isEqualToString:shortcutSearch]) {
        handled = YES;

        SecondViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"secondVC"];

        self.window.rootViewController = vc;

        [self.window makeKeyAndVisible];

    }

    else if ([shortcutItem.type isEqualToString:shortcutFavorite]) {
        handled = YES;

        ThirdViewController *vc = [storyboard instantiateViewControllerWithIdentifier:@"thirdVC"];

        self.window.rootViewController = vc;

        [self.window makeKeyAndVisible];
    }


    return handled;
}

我為主屏幕快速操作制作了一個Objective-c演示項目。

3D touch home快速動作演示:https://github.com/dakeshi/3D_Touch_HomeQuickAction

Demo項目實現了沒有Info.plist文件的靜態快速操作,以避免在啟動應用程序之前出現不必要的情況。 您可以輕松將其更改為動態快速操作。

如Apple文檔中所述,您可以在應用程序中處理快速操作:didFinishLaunchingWithOptions: method。 在這種情況下,您應該返回NO來阻止調用應用程序:performActionForShortcutItem:completionHandler:方法。

它適用於swift 3和4(僅限主屏幕快捷方式)

//Add plist items as show in image and write following method in Appdelegate
//3D Touch Method shortcuts from home screen

func application(_ application: UIApplication, performActionFor shortcutItem:UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {

if shortcutItem.type == "Share" {
    //handle action Share
    let alert = UIAlertController(title: "3D touch Share", message: "Yahoo!!! 3D touch is working👌", preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
        self.window?.rootViewController?.present(alert,animated: true,completion: nil)
    completionHandler(true)
   } else if shortcutItem.type == "Logout" {

    //handle action Type02
    let alert = UIAlertController(title: "3D touch Logout", message: "Yahoo!!! 3D touch is working👌", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
    self.window?.rootViewController?.present(alert,animated: true,completion: nil)
    completionHandler(true)
   } else {
    completionHandler(false)
  }

 }

在此輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM