为iOS添加3D touch功能

一、为ios添加3D Touch 的实现
1.在- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions方法中添加以下代码 :
UIApplicationShortcutIcon *firstItemIcon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeAdd];
    UIMutableApplicationShortcutItem *firstItem = [[UIMutableApplicationShortcutItem alloc]initWithType:@"First" localizedTitle:@"第一个按钮" localizedSubtitle:nil icon:firstItemIcon userInfo:nil];

    UIApplicationShortcutIcon *secondItemIcon = [UIApplicationShortcutIcon iconWithType:UIApplicationShortcutIconTypeShare];
    UIMutableApplicationShortcutItem *secondItem = [[UIMutableApplicationShortcutItem alloc]initWithType:@"Second" localizedTitle:@"第二个按钮" localizedSubtitle:nil icon:secondItemIcon userInfo:nil];

    application.shortcutItems = @[firstItem,secondItem];
2.实现这个方法-(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler 在这个方法中处理添加和分享的事件,代码如下:
-(void)application:(UIApplication *)application performActionForShortcutItem:(UIApplicationShortcutItem *)shortcutItem completionHandler:(void (^)(BOOL))completionHandler{

       if ([shortcutItem.type isEqual:@"First"]) {

        NSLog(@"第一个按钮事件");

    }else if([shortcutItem.type isEqual:@"share"]){

        NSLog(@"第二个按钮事件 ");

    }
}
二、通过模拟器进行调试
使用SBShortcutMenuSimulator来配置模拟器,地址https://github.com/DeskConnect/SBShortcutMenuSimulator,使模拟器支持3D Touch,
在终端中按顺序输入以下命令:
git clone https://github.com/DeskConnect/SBShortcutMenuSimulator.git

cd SBShortcutMenuSimulator

make
然后打开刚才写好的程序 运行一下打开模拟器,再去终端中按顺序输入一下命令:
xcrun simctl spawn booted launchctl debug system/com.apple.SpringBoard --environment DYLD_INSERT_LIBRARIES=$PWD/SBShortcutMenuSimulator.dylib

xcrun simctl spawn booted launchctl stop com.apple.SpringBoard

echo 'com.apple.mobilecal' | nc 127.0.0.1 8000
注意: ‘com.apple.mobilecal’ ”里边写的是自己项目的Bundle identifier. 
这行命令就是要让模拟器显示出3D Touch,每次想要显示快速入口只要重复
echo ‘com.apple.mobilecal’ | nc 127.0.0.1 8000
即可
我测试的时候crashed了,报了如下错误
Application Specific Information:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SBIconController _revealMenuForIconView:presentImmediately:]: unrecognized selector sent to instance 0x7fd412056200'
terminating with uncaught exception of type NSException
abort() called
CoreSimulator 201.3 - Device: iPhone 6s - Runtime: iOS 9.2 (13C75) - DeviceType: iPhone 6s
google了下,发现我的模拟器ios版本是9.2,需要换成9.1,需要下载ios9.1的sdk包,打开模拟器Hardware->Devices->Manage Device
点击+按钮,选择Add Simulator。在iOS version 那一行选择ios9.1,如果没有9.1,就选择去下载一个9.1。
下载完成后,再次运行,成功显示定义的两个按钮

发表评论