SBRXCallbackURLKit 1.0.0

SBRXCallbackURLKit 1.0.0

测试已测试
语言语言 Obj-CObjective C
许可证 MIT
发布时间上次发布时间2014年12月

Sebastian Rehnby 管理。



  • Sebastian Rehnby

一个简单的库,可以让您轻松地将 x-callback-url 支持添加到您的应用中。

安装

最简单的方法是使用 CocoaPods。将以下行添加到您的 Podfile 中:

pod 'SBRXCallbackURLKit'

然后运行 pod install 命令。

要手动安装,只需将 SBRXCallbackURLKit 子文件夹中的文件复制到您的 Xcode 项目中即可。

用法

您可以使用 SBRXCallbackURLKit 解析传入的 x-callback-url 操作、触发其他应用中的操作,或者结合使用两者,实现应用之间的双向交互。

处理传入的操作

要支持您的应用中的新操作,您需要处理传入的 URL。为此,您需要一个 SBRCallbackParser 的实例。最简单的方法是使用其 sharedParser 方法提供的单例。如果以这种方式使用它,确保在 application:didFinishLaunchingWithOptions: 中设置您应用的 URL 模式。

SBRCallbackParser *parser = [SBRCallbackParser sharedParser];
[parser setURLScheme:@"myapp"];

[parser addHandlerForActionName:@"myAction" handlerBlock:^BOOL(NSDictionary *parameters, NSString *source, SBRCallbackActionHandlerCompletionBlock completion) {
    NSLog(@"Action triggered with parameters: %@", parameters);

    // For two-way app communication, When you are ready to trigger the 
    // callbacks provided by the external app, call the completion 
    // block provided. This happens asynchronously for your to determine
    // when you are ready to make the callback. This callback can be omitted
    // if the action is not a two-way type action.
    completion(nil, nil, NO);

    // YES let's the parser know the action was handled, otherwise return NO
    return YES;
}];

然后,在 application:openURL:sourceApplication: 中,使用解析器处理传入的 URL。

[[SBRCallbackParser sharedParser] handleURL:url];

您还可以选择在 application:openURL:sourceApplication: 中实例化解析器并在那里添加操作处理程序。使用共享解析器的优势在下一节中进行双向通信时更为明显。

在其他应用中触发操作

在另一个应用中触发操作非常简单

SBRCallbackAction *action = [SBRCallbackAction actionWithURLScheme:@"otherapp" name:@"otherAction" parameters:@{@"text": @"Some text"}];
[action trigger];

为了允许其他应用在操作成功、失败或取消时重新打开您的应用,您可以轻松地使用上一节中描述的共享解析器注册回调处理程序。

SBRCallbackParser *parser = [SBRCallbackParser sharedParser];
[action registerCallbacksWithParser:parser successBlock:^(NSDictionary *parameters) {
    // Action successful in the other app
} failureBlock:^(NSError *error) {
    // Action failed in the other app
} cancelBlock:^{
    // Action cancelled the in other app
}];

这将向解析器添加适当的操作处理程序并执行它们,当调用 handleURL: 时。