iOS siri语音转账

前言

前一阵公司App要实现Siri语音转账的功能,百度了很久,没有找到详细的教程,于是在查阅了多年WWDC视频资料后,终于实现了,今天就这一个功能详细的讲解一下,希望对大家有所帮助。

一、工程基本配置

创建一个普通的xcode工程,然后进行如下配置
1、在工程的 Signing&Capabilities 中,点击 +Capability ,添加Siri

Signing&Capabilities.png

添加完成后是这个样子的
siri.png

2、添加siri权限申请
权限申请.png

3、在 AppDelegate 中,导入 #import <Intents/Intents.h> 头文件,添加如下代码

#import "AppDelegate.h"
#import <Intents/Intents.h>

@interface AppDelegate ()

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    
    [INPreferences requestSiriAuthorization:^(INSiriAuthorizationStatus status) {
        NSLog(@"%ld", (long)status);
    }];
    
    return YES;
}

此时运行工程,会出现Siri权限申请,点击

权限提示.png

至此,工程基本配置完成,接下来进行第二步。

二、添加Siri扩展

1、依次点击 Xcode -> File -> New -> Target ,选择 iOS -> Intents Extension

Intents Extension.png

填写 Product Name 点击 Finish 完成操作。 Include UI Extension 默认勾选,不要取消选中,后续需要用到。
Extension.png

此时会弹出提示框,选择 Active
Active.png

至此,会新增两个 TargetSIRIPaymentExtensionSIRIPaymentExtensionUI ,接下来我们进行第三步。

三、 SIRIPaymentExtensionSIRIPaymentExtensionUI 配置

1、对 SIRIPaymentExtension -> info.plist -> NSExtension -> NSExtensionAttributes 中的 IntentsRestrictedWhileLocked 以及 IntentsSupported 进行调整,删除现有的配置,添加 INSendPaymentIntent (转账),调整后如下

infoPlist.png

IntentsSupported表示所支持的功能,IntentsRestrictedWhileLocked表示解锁手机才能使用的功能,因为转账属于隐私的功能,所以需要解锁手机才能使用。
2、对 SIRIPaymentExtensionUI 也进行相同的配置, SIRIPaymentExtensionUI 只需要配置 IntentsSupported ,调整后如下。
infoPlist2.png

准备工作基本完成,接下来进入代码编写。

四、 SIRIPaymentExtension 编写代码

1、 SIRIPaymentExtension 目录,创建一个继承自 NSObject 的转账处理类,这里我们命名为 SIRISendPaymentIntentHandler ,点击 Next ,Targets选择 SIRIPaymentExtension

SIRISendPaymentIntentHandler.png

2、调整默认创建的 IntentHandler 代码结构,删除无用代码,调整后的代码如下

//
//  IntentHandler.m
//  SIRIPaymentExtension
//
//  Created by 宋法键 on 2020/9/24.
//  Copyright © 2020 SFJ. All rights reserved.
//

#import "IntentHandler.h"
#import "SIRISendPaymentIntentHandler.h"

@interface IntentHandler ()

@end

@implementation IntentHandler

- (id)handlerForIntent:(INIntent *)intent {
    
    // 如果是转账请求,那么返回我们自己创建的转账处理类 SIRISendPaymentIntentHandler
    if ([intent isKindOfClass:[INSendPaymentIntent class]]) {
        return [[SIRISendPaymentIntentHandler alloc] init];
    }
    
    return self;
}

@end

3、接下来我们编写 SIRISendPaymentIntentHandler 中的代码
为实现Siri转账,首先我们要添加 <INSendPaymentIntentHandling> 代理方法

#import "SIRISendPaymentIntentHandler.h"
#import <Intents/Intents.h>

@interface SIRISendPaymentIntentHandler ()<INSendPaymentIntentHandling>

@end

然后实现以下几个功能

  • 解析收款人( Resolve
@implementation SIRISendPaymentIntentHandler
//Resolve - payee 解析收款人 iOS10.0
- (void)resolvePayeeForSendPayment:(INSendPaymentIntent *)intent withCompletion:(void (^)(INPersonResolutionResult * _Nonnull))completion {
    if (intent.payee == nil || !intent.payee.displayName.length) {
        //如果收款人为空,那么请求siri,需要收款人或者不处理
        //Siri对中文名字的识别有些问题,所以最好写notRequired
        INPersonResolutionResult *resolutionResult = [INPersonResolutionResult notRequired];
        completion(resolutionResult);
    }
    else {
        //收款人不为空,确认收款人信息
        INPersonResolutionResult *resolutionResult = [INPersonResolutionResult successWithResolvedPerson:intent.payee];
        completion(resolutionResult);
    }
}

//Resolve - payee 解析收款人 iOS11.0
- (void)resolvePayeeForSendPayment:(INSendPaymentIntent *)intent completion:(void (^)(INSendPaymentPayeeResolutionResult * _Nonnull))completion  API_AVAILABLE(ios(11.0)){
    if (intent.payee == nil) {
        INSendPaymentPayeeResolutionResult *resolutionResult = [INSendPaymentPayeeResolutionResult notRequired];
        completion(resolutionResult);
    }
    else {
        INSendPaymentPayeeResolutionResult *resolutionResult = [INSendPaymentPayeeResolutionResult successWithResolvedPerson:intent.payee];
        completion(resolutionResult);
    }
}
  • 解析货币以及金额( Resolve
//Resolve - currency 解析货币 iOS10.0
- (void)resolveCurrencyAmountForSendPayment:(INSendPaymentIntent *)intent withCompletion:(void (^)(INCurrencyAmountResolutionResult * _Nonnull))completion {
    INCurrencyAmount *currencyAmount = intent.currencyAmount;
    if (currencyAmount == nil) {
        //金额为空,请求siri,需要转账金额
        INCurrencyAmountResolutionResult *resolutionResult = [INCurrencyAmountResolutionResult needsValue];
        completion(resolutionResult);
    }
    else if ([currencyAmount.currencyCode isEqualToString:@"CNY"]) {
        //如果币种不是人民币,将接收到的币种转化为人民币
        INCurrencyAmount *newCurrencyAmount = [[INCurrencyAmount alloc] initWithAmount:currencyAmount.amount currencyCode:@"CNY"];
        INCurrencyAmountResolutionResult *resolutionResult = [INCurrencyAmountResolutionResult successWithResolvedCurrencyAmount:newCurrencyAmount];
        completion(resolutionResult);
    }
    else {
        INCurrencyAmountResolutionResult *resolutionResult = [INCurrencyAmountResolutionResult successWithResolvedCurrencyAmount:currencyAmount];
        completion(resolutionResult);
    }
}

//Resolve - currency 解析货币单位 iOS11.0
- (void)resolveCurrencyAmountForSendPayment:(INSendPaymentIntent *)intent completion:(void (^)(INSendPaymentCurrencyAmountResolutionResult * _Nonnull))completion  API_AVAILABLE(ios(11.0)){
    INCurrencyAmount *currencyAmount = intent.currencyAmount;
    if (currencyAmount == nil || currencyAmount.amount == nil) {
        INSendPaymentCurrencyAmountResolutionResult *resolutionResult = [INSendPaymentCurrencyAmountResolutionResult needsValue];
        completion(resolutionResult);
    }
    else if (![currencyAmount.currencyCode isEqualToString:@"CNY"]) {
        //货币格式转化为人民币
        INCurrencyAmount *newCurrencyAmount = [[INCurrencyAmount alloc] initWithAmount:currencyAmount.amount currencyCode:@"CNY"];
        INSendPaymentCurrencyAmountResolutionResult *resolutionResult = [INSendPaymentCurrencyAmountResolutionResult successWithResolvedCurrencyAmount:newCurrencyAmount];
        completion(resolutionResult);
    } else {
        INSendPaymentCurrencyAmountResolutionResult *resolutionResult = [INSendPaymentCurrencyAmountResolutionResult successWithResolvedCurrencyAmount:currencyAmount];
        completion(resolutionResult);
    }
}

  • 确认货币以及金额( Confirm
//Confirm - 确认金额信息
- (void)confirmSendPayment:(INSendPaymentIntent *)intent completion:(void (^)(INSendPaymentIntentResponse * _Nonnull))completion {
    NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([INSendPaymentIntent class])];
    userActivity.title = @"转账";
    userActivity.userInfo = @{@"displayName": intent.payee.displayName?:@"",
                              @"amount": intent.currencyAmount.amount};
    
    //确认支付货币,否则系统会默认展示USD(美元)
    INPaymentMethod *paymentMethod = [INPaymentMethod applePayPaymentMethod];
    //status字段决定了siri转账页面底部的UI
    INPaymentRecord *paymentRecord = [[INPaymentRecord alloc] initWithPayee:intent.payee payer:nil currencyAmount:intent.currencyAmount paymentMethod:paymentMethod note:intent.note status:(INPaymentStatusPending)];
    INSendPaymentIntentResponse *sendPaymentIntentResponse = [[INSendPaymentIntentResponse alloc] initWithCode:(INSendPaymentIntentResponseCodeReady) userActivity:userActivity];
    sendPaymentIntentResponse.paymentRecord = paymentRecord;
    completion(sendPaymentIntentResponse);
}
  • 处理请求( Handle
//Handle - 转账处理
- (void)handleSendPayment:(INSendPaymentIntent *)intent completion:(void (^)(INSendPaymentIntentResponse * _Nonnull))completion {
    NSUserActivity *userActivity = [[NSUserActivity alloc] initWithActivityType:NSStringFromClass([INSendPaymentIntent class])];
    userActivity.title = @"转账";
    userActivity.userInfo = @{@"displayName": intent.payee.displayName?:@"",
                              @"amount": intent.currencyAmount.amount};
    INSendPaymentIntentResponse *sendPaymentIntentResponse = [[INSendPaymentIntentResponse alloc] initWithCode:(INSendPaymentIntentResponseCodeInProgress) userActivity:userActivity];
    completion(sendPaymentIntentResponse);
}

4、编写 IntentViewController 中的代码

//
//  IntentViewController.m
//  MobileBankSiriExtensionUI
//
//  Created by 宋法键 on 2020/7/29.
//  Copyright © 2020 Alibaba. All rights reserved.
//

#import "IntentViewController.h"
#import <Intents/Intents.h>

// As an example, this extension's Info.plist has been configured to handle interactions for INSendMessageIntent.
// You will want to replace this or add other intents as appropriate.
// The intents whose interactions you wish to handle must be declared in the extension's Info.plist.

// You can test this example integration by saying things to Siri like:
// "Send a message using <myApp>"

@interface IntentViewController ()< INUIHostedViewSiriProviding>
@property (weak, nonatomic) IBOutlet UILabel *amountLabel;
@end

@implementation IntentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

#pragma mark - INUIHostedViewSiriProviding

- (BOOL)displaysPaymentTransaction {
    return YES;;
}

#pragma mark - INUIHostedViewControlling
- (void)configureWithInteraction:(INInteraction *)interaction context:(INUIHostedViewContext)context completion:(void (^)(CGSize))completion {
    if ([interaction.intent isKindOfClass:[INSendPaymentIntent class]] && (interaction.intentHandlingStatus == INIntentHandlingStatusReady)) {
        INSendPaymentIntent *sendPaymentIntent = (INSendPaymentIntent *)interaction.intent;
        self.amountLabel.text = [NSString stringWithFormat:@"¥%.2f", sendPaymentIntent.currencyAmount.amount.doubleValue];
        if (completion) {
            completion(CGSizeMake([self desiredSize].width, 200));
        }
    } else {
        if (completion) {
            completion(CGSizeZero);
        }
    }
}

// Prepare your view controller for the interaction to handle.
- (void)configureViewForParameters:(NSSet <INParameter *> *)parameters ofInteraction:(INInteraction *)interaction interactiveBehavior:(INUIInteractiveBehavior)interactiveBehavior context:(INUIHostedViewContext)context completion:(void (^)(BOOL success, NSSet <INParameter *> *configuredParameters, CGSize desiredSize))completion  API_AVAILABLE(ios(11.0)){
    // Do configuration here, including preparing views and calculating a desired size for presentation.

    if ([interaction.intent isKindOfClass:[INSendPaymentIntent class]] &&
        (interaction.intentHandlingStatus == INIntentHandlingStatusReady) &&
        [[parameters anyObject].parameterKeyPath isEqualToString:@"currencyAmount"]) {
        INSendPaymentIntent *sendPaymentIntent = (INSendPaymentIntent *)interaction.intent;
        self.amountLabel.text = [NSString stringWithFormat:@"¥%.2f", sendPaymentIntent.currencyAmount.amount.doubleValue];
        completion(YES, parameters, CGSizeMake([self desiredSize].width, 200));
    } else {
        completion(YES, parameters, CGSizeZero);
    }
}

- (CGSize)desiredSize {
    return [self extensionContext].hostedViewMaximumAllowedSize;
}

@end

MainInterface.storyboard 中的截图如下

MainInterface.png

至此,Siri转账的处理完成,我们来开一下运行的效果


first.png

second.png

third.png

但是,我们还没有接收Siri传递过来的转账信息,所以,我们需要在 AppDelegate 中接收以下传递过来的信息。

五、转账信息接收与处理

Siri打开App以后我们需要接收以下传递过来的收款人以及金额,因此,在AppDelegate添加如下代码

- (BOOL)application:(UIApplication *)application continueUserActivity:(NSUserActivity *)userActivity restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler
{
    
    if (@available(iOS 10.0, *)) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if ([userActivity.interaction.intent isKindOfClass:[INSendPaymentIntent class]]) {
                INSendPaymentIntent *sendPaymentIntent = (INSendPaymentIntent *)(userActivity.interaction.intent);
                NSString *displayName = sendPaymentIntent.payee.displayName;
                NSString *amount = [NSString stringWithFormat:@"%@", sendPaymentIntent.currencyAmount.amount];
                NSLog(@"displayName: %@ -- amount: %@", displayName, amount);
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    
                    NSString *title = [NSString stringWithFormat:@"收款人:%@", displayName];
                    NSString *message = [NSString stringWithFormat:@"金额:%@", amount];
                    
                    UIAlertView *alt = [[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:@"好" otherButtonTitles: nil];
                    [alt show];
                    
                });
            }
        });
    }
    
    return YES;
}
alert.png

到这里,你已经可以拿到所需要的收款人姓名以及金额了,接下来就看自己的业务需要,然后进行处理了

小技巧

选中 SIRIPaymentExtension target 然后 Edit Scheme ,在 Run -> Info -> Siri Intent Query 添加你想要说的信息,比如“给张帆转账100元”,然后直接运行,即可,就不需要傻傻的对着手机说了。

Query.png

https://github.com/belink-QD/SIRIPayment

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 214,658评论 6 496
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,482评论 3 389
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 160,213评论 0 350
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,395评论 1 288
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,487评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,523评论 1 293
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,525评论 3 414
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,300评论 0 270
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,753评论 1 307
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,048评论 2 330
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,223评论 1 343
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,905评论 5 338
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,541评论 3 322
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,168评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,417评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,094评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,088评论 2 352