必须使用通知服务应用扩展程序来显示远程通知中的媒体?

时间:2017-02-02 11:32:56

标签: ios push-notification onesignal

我正在尝试使用媒体附件发送iOS推送通知(图片网址)我已经使用适用于iOS的OneSignal SDK 2.2.2但它根本不起作用。在下面的article中,您似乎不必实现服务扩展来在通知中显示图像。 (iOS 10)。

我是否需要创建Notification Service应用扩展程序?

1 个答案:

答案 0 :(得分:0)

是的,在将推送通知有效负载提交回操作系统以显示给用户之前,需要实施推送通知有效负载的handle通知服务扩展。

实施例: 如果这是收到的有效载荷:

    {
      "aps": {
          "alert": {
            "title": "My title",
            "subtitle": "My title"
            },
           "mutable-content": 1,
           "category": "<your_notification_category>"
          },
        "data": {
          "url": "<img_url>"
        }
    }

您的服务必须下载图像,然后将下载的本地URL捆绑为UNNotificationAttachment,然后再将其发送到操作系统

- (void)didReceiveNotificationRequest:(UNNotificationRequest *)request withContentHandler:(void (^)(UNNotificationContent * _Nonnull))contentHandler {
        self.contentHandler = contentHandler;
        self.bestAttemptContent = [request.content mutableCopy];

        // Modify the notification content here...

        if (request.content.userInfo[@"data"] && [request.content.userInfo[@"data"] isKindOfClass:[NSDictionary class]]) {
            NSDictionary *data = request.content.userInfo[@"data"];
            NSLog(@"%@", data);
            NSURL *dataURL = [NSURL URLWithString:data[@"url"]];
            self.task = [[NSURLSession sharedSession] downloadTaskWithURL:dataURL completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {

                if (location) {
                    // Get the location URL and change directory

                    NSString *tempDirectory = NSTemporaryDirectory();
                    NSURL *fileURL = [NSURL fileURLWithPath:tempDirectory];
                    fileURL = [fileURL URLByAppendingPathComponent:[dataURL lastPathComponent]];
                    NSError *error;
                    if ([[NSFileManager defaultManager] fileExistsAtPath:[fileURL path]]) {
                        [[NSFileManager defaultManager] removeItemAtPath:[fileURL path] error:&error];
                    }
                    [[NSFileManager defaultManager] moveItemAtURL:location toURL:fileURL error:&error];

                    // Create UNNotificationAttachment for the notification

                    UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"" URL:fileURL options:nil error:nil];
                    self.bestAttemptContent.attachments = @[attachment];
                }

                self.contentHandler(self.bestAttemptContent);
            }];
            [self.task resume];

        } else {
            self.contentHandler(self.bestAttemptContent);
        }

    } 
}