如何将媒体附件添加到iOS 10应用中的推送通知?

如何将媒体附件添加到iOS 10应用中的推送通知?

问题描述:

有多个示例应如何设置项目以添加使用“媒体附件”技术显示图像的丰富通知。我读过大部分的东西,但我错过了,因为我的项目不具有这种负载(用APNS工具和Boodle测试)显示任何通知丰富:如何将媒体附件添加到iOS 10应用中的推送通知?

{ 
    "aps":{ 
     "alert":{ 
      "title": "Rich test", 
      "body": "Dancing Banana" 
     }, 
     "mutable-content": 1 
    } 
} 

通知是可见的,但在3D触控,没有额外的信息显示(如图像或修改后的标题)。通知扩展断点和NSLog消息也不起作用。

这里是我的演示项目:https://github.com/gklka/RichTest

我所做的:

  1. 创建一个新的项目
  2. 实施的iOS风格的授权:
 
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter]; 
    [center requestAuthorizationWithOptions:UNAuthorizationOptionAlert completionHandler:^(BOOL granted, NSError * _Nullable error) { 

     if (granted) { 
      NSLog(@"Granted"); 

      [[UIApplication sharedApplication] registerForRemoteNotifications]; 

     } else { 
      NSLog(@"Error registering: %@", error); 
     } 

    }]; 
  1. 将调试添加到AppDelegate:
 
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { 
    NSLog(@"Token: %@", deviceToken); 
} 

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error { 
    NSLog(@"Error: %@", error); 
} 
  1. 添加一个新的目标到项目:通知服务扩展:
  2. Add new target

    1. 添加banana.gif到项目

    2. 添加代码以将香蕉附件添加到NotificationService.m

    3.  
          self.bestAttemptContent.title = [NSString stringWithFormat:@"%@ [modified]", self.bestAttemptContent.title]; 
      
          // Add image attachment 
          NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"banana" withExtension:@"gif"]; 
          NSError *error; 
          UNNotificationAttachment *attachment = [UNNotificationAttachment attachmentWithIdentifier:@"banana" URL:fileURL options:nil error:&error]; 
          self.bestAttemptContent.attachments = @[attachment]; 
      

      我错过了什么?

      附加信息:当我使用本地通知而不是远程通知时,同样的工作。

    开始=>
开始=>

你是那里的大部分。您要发送附件的方式通常是作为有效负载中的URL。但是,如果您想对附件进行硬编码,就像您的代码那样,我认为它会起作用,但我认为您错过了一个关键组件。我认为服务扩展无法访问主包或其资源。如果您向服务扩展添加资源并尝试加载该资源(使用类似[NSBundle bundleForClass:[NotificationService class]]),我怀疑它会起作用。

但是,如果您将URL作为有效负载的一部分发送,那么您将从该URL加载映像,而不是该包。在那种情况下,我敢肯定你还必须在NSURL上使用startAccessingSecurityScopedResource(以及stopAccessingSecurityScopedResource)。

希望有帮助!

+0

好主意,我试过了,有两个问题:1.为什么“[modified]”标题修改不起作用呢? 2.我修改了URL上的项目以支持文件下载,并发送以下内容:https://gist.github。com/gklka/9802bb56340c38a7a481cde2c4fcaa70它似乎也没有工作。 – gklka

+0

'serviceExtensionTimeWillExpire()'是否被调用?如果你从Xcode(而不是应用程序)运行扩展,你可以在任何一种方法中打断点吗? – Jerry

+0

既没有'NSLog',也没有将断点放入'NotificationService.m'似乎工作。也许我错过了什么?你能否在GitHub上检查我的项目? https://github.com/gklka/RichTest – gklka