TwinPush Receipt Extension
为TwinPush平台原生iOS SDK提供的伴侣库,添加通知收据支持。
安装
创建通知服务扩展
苹果推送通知服务将通知直接发送到操作系统而不是应用。为了拦截通知并发送发送收据,我们将使用通知服务扩展。要创建一个,在XCode中执行文件
-> 新建
-> 目标
,选择通知服务扩展。
为扩展输入一个名称,并确保将其嵌入到您的应用程序中。
它将创建一个新的目标,包含一个名为NotificationService
的单个类。我们稍后将编辑此文件。
安装扩展库
通知服务扩展实际上是一个与应用程序分离的不同目标,它不包含应用程序中包含的任何库,因此我们必须导入一个新的框架来向TwinPush平台报告接收确认。
我们创建了一个简化的SDK版本,它包含一个方法,用于向TwinPush报告接收确认。
使用CocoaPods
当使用CocoaPods时,将对TwinPushReceiptExtension
的依赖添加到您的通知服务扩展目标。例如,您的Podfile
可能看起来像这样
target 'MyApp' do
use_frameworks!
pod 'TwinPushSDK'
end
target 'MyAppNotificationExtension' do
use_frameworks!
pod 'TwinPushReceiptExtension'
end
请注意,TwinPushReceiptExtension
被添加到扩展目标,而不是应用程序目标。请确保目标名称与创建通知服务扩展时输入的名称相匹配。
手动复制源文件
另一种在您的扩展中包含库的方法是将源文件手动复制到您的项目中。要做到这一点,请访问Github仓库并复制提供的库代码到您的通知服务扩展目录。
确保将此文件包含在您的通知服务扩展目标中
发送通知回执
安装完成后,我们可以回到之前创建的NotificationService
类,并将接收到的通知报告给TwinPush平台。由于这是一个不同的目标,需要再次设置App ID和环境URL。
// Objective-C
#import "NotificationService.h"
@import TwinPushReceiptExtension; // Exclude this import if not using CocoaPods
@interface NotificationService ()
@property(nonatomic, strong) TPNotificationReceiptService* receiptService;
@end
@implementation NotificationService
- (instancetype)init {
if (self = [super init]) {
self.receiptService = [[TPNotificationReceiptService alloc] initSubdomain:@"TP_SUBDOMAIN"];
}
return self;
}
- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
UNMutableNotificationContent* bestAttemptContent = [request.content mutableCopy];
#ifdef DEBUG
// Use this to verify that the extenion is being called
bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", bestAttemptContent.title];
#endif
[_receiptService reportNotificationReceiptWithNotification:request.content onComplete:^{
contentHandler(bestAttemptContent);
}];
}
@end
// Swift
import UserNotifications
import TwinPushReceiptExtension // Exclude this import if not using CocoaPods
class NotificationService: UNNotificationServiceExtension {
let receiptService = TPNotificationReceiptService(subdomain: "TP_SUBDOMAIN")
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
if let bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) {
#if DEBUG
bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
#endif
receiptService.reportNotificationReceipt(notification: request.content) {
contentHandler(bestAttemptContent)
}
}
}
}