IBM Cloud Docs
使用Event Notifications创建并向iOS移动设备发送推送通知

使用Event Notifications创建并向iOS移动设备发送推送通知

创建 Event Notifications 服务,为 Apple 推送通知服务 (APN) 添加推送目标,并将消息发送到 iOS 设备。

什么是 Event Notifications?

Event Notifications是一项事件通知路由服务,可通知您 "IBM Cloud账户中发生的重要事件,或使用网络钩子触发自动操作。 您可以将事件通知从 IBM Cloud 服务 (例如 Availability Monitoring) 过滤和路由到电子邮件,SMS,推送通知 (FCM 或 APN) 和 Webhook。

客户机如何使用 iOS 推送通知?

下图显示客户机如何使用 iOS 推送通知。

客户如何使用推送通知
使用推送

目标

本教程向您展示了如何发送推送通知,如下所示:

  • 使用Event Notifications 创建移动应用程序。
  • 获取 APN 凭证。
  • 下载代码并完成通知设置。
  • 配置 iOS Push Notifications 并将其发送到移动设备。

准备工作

您必须具备以下先决条件:

  • IBM Cloud 帐户。 如果您没有帐户,请 创建 IBM Cloud 帐户
  • Event Notifications 实例。
  • IAM API 密钥,用于允许 SDK 访问您的帐户。 在 此处创建一个。
  • Xcode 9.3+
  • Swift 4.2+
  • iOS 10.0+

创建Event Notifications服务实例

  • 登录到 IBM Cloud 帐户
  • IBM Cloud 目录 中,搜索 Event Notifications > Event Notifications
  • 从受支持区域列表中选择 Region,然后选择 pricing plan
  • 提供 "Service name
  • 选择 "resource group
  • 通过单击复选框来接受许可协议和条款。
  • 单击 Create

获取 APN 凭证

对于 iOS 设备和应用程序,Apple 推送通知服务 (APNs) 允许应用程序开发者从 Event Notifications 上的 IBM Cloud 服务实例(提供者)将远程通知发送到 iOS 设备和应用程序。 消息会发送到设备上的目标应用程序。

您需要获取并配置 APNs 凭证。 APNs 证书由 Event Notifications 服务安全地进行管理,并用于连接到 APNs 服务器(提供者)。

注册应用程序标识

应用程序标识(捆绑标识)是用于标识特定应用程序的唯一标识。 每个应用程序都需要应用程序标识。 推送通知服务等服务配置到App ID。

  • 转至 Apple 开发者门户网站,然后选择 证书,标识和概要文件

    Certificates, Identifiers & Profiles
    Certificates, Identifiers & Profiles

  • 转至 Identifiers > Add identifier button

    标识符按钮{: caption="标识符按钮标识符" caption-side="bottom"}

  • 单击“添加新 Identifier”按钮。

    添加新标识符按钮
    新标识符

  • 选择“应用程序标识”选项。

    应用程序 ID 选项
    *应用程序 ID 选项
    应用程序 ID 选项

  • 选择类型并点击 "Continue

    App ID type
    App ID type

  • 为 App ID Prefix 提供字符串。 在 Description 字段中提供应用程序名称。 例如,Event Notifications iOS 应用程序。

  • 对于 Bundle ID,选择 显式 并提供捆绑软件标识值。 建议提供逆向域名样式的字符串。 例如,com.ibm.cloud.en.app

    创建新的App ID
    新的App ID

  • 从“功能”中选择 Push Notifications 复选框,然后单击 Continue

    启用推送通知
    启用推送通知*启用推送

  • 查看设置并点击 "Register > Done

现在,您的应用程序标识已注册。

App ID
Newly created App ID

创建开发和分发 APNs SSL 证书

在获取 APNs 证书之前,必须首先生成一个证书签名请求 (CSR),然后将其提交给 Apple(认证中心 (CA))。 CSR 中包含您公司的标识信息,以及您用于签署 Apple 推送通知的公用密钥和专用密钥信息。 然后,在 iOS 开发者门户网站上生成 SSL 证书。 该证书与其公用密钥和专用密钥一起存储在“钥匙串访问”中。

您可以在两种模式下使用 APNs:

  • 沙箱模式,用于开发和测试。
  • 生产模式,用于通过 App Store(或其他企业分发机制)分发应用程序。

必须分别针对开发环境和分发环境获取不同的证书。 证书与接收远程通知的应用程序的应用程序标识相关联。 对于生产,您最多可以创建两个证书。IBM Cloud 使用证书与 APN 建立 SSL 连接。

创建 APN p12 证书

  • 转至 Apple 开发者门户网站,然后选择“证书”,“标识”和“概要文件”。

    Certificates, Identifiers & Profiles
    Certificates, Identifiers & Profiles

  • Identifiers area 中,选择 App ID。

    标识符选项卡{: caption="标识符选项卡 标识符" caption-side="bottom"}

  • Select the Push Notifications check-box OR select the Edit option.

    推送通知复选框
    推送通知
    *

    • 在开发 SSL 证书窗格中,单击创建证书...
    • 在生产 SSL 证书窗格中,单击创建证书...

    证书类型{: caption="证书" caption-side="bottom"}

  • 使用 Mac 上的 Keychain Access 应用程序创建证书签名请求 (CSR)。

  • 从菜单中选择 "Keychain Access > Certificate Assistant > Request a Certificate From a Certificate Authority…

    申请新证书
    申请新证书
    * 申请新证书类型

  • 在“证书信息”中,输入与 App Developer 账户关联的电子邮件地址和常用名。 提供有意义的名称来帮助您识别此为开发(沙箱)证书还是分发(生产)证书;例如,sandbox_apns_certificateproduction_apns_certificate

  • 选择 "Saved to disk 将 ".certSigningRequest 文件下载到 Mac,然后点击 "Continue

    Certificate details
    Certificate details

  • Save As 菜单选项中,命名 .certSigningRequest 文件,选择必须保存该文件的位置,然后单击 Save

    保存 CSR 文件
    保存 CSR

  • 单击 Done。 您现在就有一个 CSR 了。

    caption-side=bottom"
    创建的
    的 CSR*

  • 返回苹果开发者门户,在上传 CSR 文件选项中点击选择文件,然后选择文件 "CertificateSigningRequest.certSigningRequest。 点击 "Continue

    上传 CSR 文件
    上传 CSR 文件*上传 CSR

  • 单击 Download。 这将下载 aps_development.cer 文件。

    ![下载证书](images/en-apns-p12-download-cer.png "下载证书*下载" caption-side="bottom"}"){: caption="

  • 找到新安装的证书。 双击该证书,以将其安装到“密钥链访问”中。

  • 在 Mac 上,转至 Keychain Access > My Certificates

  • 选择证书和私钥,然后选择 "Export,将证书转换为个人信息交换格式(.p12 格式)。

    出口证书
    出口

  • 在 "Save As 字段中,为证书提供一个有意义的名称。 例如,sandbox-apns.p12production-apns.p12,然后单击 Save

    caption-side=bottom"
    保存证书

  • 在“Enter a password 字段中输入密码以保护导出的项目,然后点击”OK。 您可以使用此密码在Event Notifications服务控制台配置 APN 设置。

    保护证书
    保护证书*保护

  • Key Access 应用程序会提示你从“钥匙串”屏幕导出密钥。 输入 Mac 的管理密码以允许系统导出这些项目,然后选择“始终允许”选项。 在所选位置生成.p12证书。

创建 APN p8 令牌

  • 转至 Apple Developer Portal,然后选择 Certificates, Identifiers & Profiles

    Certificates, Identifiers & Profiles
    Certificates, Identifiers & Profiles

  • 转至 Keys 选项卡。

    按键选项卡
    * 按键选项卡* 按键

  • 输入 Key Name 并启用 APN,然后单击 continue

    P8 token details
    P8 token details

  • 单击 Register

    ![注册p8标记 * 注册p8 "){: caption="](images/en-apns-p8-register.png " p8 " caption-side="bottom"}

  • 请确保在注册后在新的重定向页面下载密钥,因为这是一次性活动。

KeyID 可视为文件的一部分并显示在 UI 中,此 KeyID 用于注册 APNS 证书。TeamID 由 apple 为开发者帐户提供,可以在“团队名称”旁边看到。TeamID 用于注册 APNS 证书。可以将 BundleID 注册为与 P12 证书相同的证书。

添加通用 API 源

请执行以下步骤:

  • 转至 Event Notifications 仪表板的 Sources 部分。
  • 单击 Add 并选择 API 源。
  • 输入名称和可选描述,然后单击 Add

创建Event Notifications目的地

在 Event Notifications 控制台中单击 Destinations,然后添加以下目标详细信息:

  • Name: 添加目标的名称。
  • Description: 添加目标的可选描述。
  • Type: 从下拉列表中选择 iOS Push Notifications 类型。
  • 选择目标计划: 生产前目标或生产目标。
    • Pre-production destination-针对开发和测试环境,选择此目标作为低成本推送目标。
    • Production destination-使用此目标的完整功能。 允许无限设备和外发信息。
  • 使用基于 Authentication Type 的详细信息更新 iOS 推送凭证,然后选择 Environment
    • 如果证书类型为 p8,请上载 .p8 文件并提供 KeyIDTeamIDBundleID
    • 如果证书类型为 p12,请上载 p12 证书并提供证书 password
  • 单击 Add

创建 Event Notifications 主题

在 Event Notifications 控制台中选择 Topics,然后单击 Create。 输入以下主题详细信息:

  • Name: 输入主题的名称。
  • Description: 添加主题的可选描述。
  • Source:从下拉列表中选择来源。
  • Event type: 从下拉列表中选择事件类型。
  • Event sub type 从事件子类型下拉列表中选择事件子类型。
  • Severity: 从严重性下拉列表中选择严重性。
  • Advanced conditions: 编写您自己的定制条件,必须遵循 jsonpath 规范

创建Event Notifications订阅

在 Event Notifications 控制台中单击 Subscriptions。 输入以下订购详细信息:

  • Click 创建以显示预订向导。
  • 填写以下订购信息:
    • Subscription name: 预订的名称。
    • Subscription description: 添加可选描述。
  • Subscribe to a topic 部分下,从下拉列表中选择主题,然后从目标下拉列表中选择目标。
  • Destination type: 在 Destination 下选择类型,然后单击 Add

设置 Event Notifications IOS SDK

iOS SDK 使 iOS 应用程序能够接收推送通知。 完成以下步骤以安装 Event Notifications iOS SDK,初始化 SDK 并注册 iOS app的通知。

安装植入

此 SDK 的当前版本为: 0.0.1

要使用 Event Notifications iOS 目标 SDK,请定义包含服务的工件坐标 (组标识,工件标识和版本) 的依赖关系,如下所示:

CocoaPods

use_frameworks!

target 'MyApp' do
   pod 'ENPushDestination', '~> 0.0.1'
end

Carthage

要使用 Carthage 安装 ENPushDestination,请将以下内容添加到 Cartfile。

github "IBM/event-notifications-destination-ios-sdk" ~> 0.0.1

然后,运行以下命令以构建依赖关系和框架:

carthage update --platform iOS

Swift 包管理器

将以下内容添加到 Package.swift 文件以将 ENPushDestination 标识为依赖关系。 当您使用 swift 构建构建项目时,包管理器会克隆 ENPushDestination。

dependencies: [
   .package(url: "https://github.com/IBM/event-notifications-destination-ios-sdk", from: "0.0.1")
]

安装-初始化 SDK

完成以下步骤以使 iOS 应用程序能够接收通知。

  1. .swift 文件中添加 import 语句。

    import ENPushDestination
    
  2. 初始化ENPushDestinationSDK

    let instanceGUID = "<instance_guid>>";
    let destinationID = "<instance_destination_id>";
    let apiKey = "<instance_apikey>";
    
    let enPush = ENPush.sharedInstance
    enPush.setCloudRegion(region: .usSouth)
    enPush.initialize(instanceGUID, destinationID, apiKey)
    
    • region: Event Notifications 实例的区域。 例如,Region.usSouth

注册以获取通知

使用 ENPush.registerDevice() API 在 Event Notifications 服务中向 iOS 目标注册设备。

支持以下选项:

  • 注册时不带userId:

    /**Register iOS devices*/
    enPush.registerWithDeviceToken(deviceToken: "<apns-device-token>") { response, statusCode, error in
       print(response?.id ?? "")
    }
    
  • 向 UserId注册。 对于基于 userId 的通知,注册方法再接受一个参数- userId

    /**Register iOS devices*/
    enPush.registerWithDeviceToken(deviceToken: "<apns-device-token>", withUserId: "userId") { response, statusCode, error in
    
       print(response?.id ?? "")
    
    }
    

    userId 用于传递用于注册 Event Notifications的唯一 userId 值。

从通知注销

使用以下代码片段从 Event Notifications注销。

enPush.unregisterDevice { response, statusCode, error in
   /**.....*/
}

要从基于 UserId 的注册中注销,必须调用注册方法。 请参阅 注册以获取通知 中的 Register without userId option

Event Notifications 目标标记预订

预订标记

subscribe API 为给定标记预订设备。 设备订阅特定标签后,就能接收为该标签发送的通知。

将以下代码片段添加到 iOS 移动应用程序以预订标记列表。

// Subscribe to the given tag
enPush.subscribeToTags(tagName: "<tag_name>") { response, statusCode, error in
   /**.....*/
});

检索预订的标记

retrieveSubscriptionsWithCompletionHandler API 返回设备预订的标记的列表。 在移动应用程序中使用以下代码片段来获取预订列表。

// Get a list of tags that to which the device is subscribed.
enPush.retrieveSubscriptionsWithCompletionHandler { response, statusCode, error in
   /**.....*/
}

从标记取消预订

unsubscribeFromTags API 从列表标记中除去设备预订。 使用以下代码片段来允许您的设备从标记中取消预订。

// unsubscibe from the given tag ,that to which the device is subscribed.
enPush.unsubscribeFromTags(tagName: "<tag_name>") { response, statusCode, error in
   /**.....*/
}

在 iOS 设备上接收推送通知

要在iOS设备上接收推送通知,请在应用程序的 "appDelegate.swift 中添加以下Swift方法:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

   //UserInfo dictionary will contain data sent from the server
}

通知选项

支持以下通知选项。

交互式通知

  1. 要启用交互式推送通知,必须将通知操作参数作为通知对象的一部分传递。 以下是用于启用交互式通知的样本代码:
let actionOne = ENPushNotificationAction(identifierName: "FIRST", buttonTitle: "Accept", isAuthenticationRequired: false, defineActivationMode: .foreground)

let actionTwo = ENPushNotificationAction(identifierName: "SECOND", buttonTitle: "Reject", isAuthenticationRequired: false, defineActivationMode: .destructive)

let category = ENPushNotificationActionCategory(identifierName: "category", buttonActions: [actionOne, actionTwo])

let notificationOptions = ENPushClientOptions()
notificationOptions.setInteractiveNotificationCategories(categoryName: [category])
enPush.initialize(instanceGUID, destinationID, apiKey, notificationOptions)
  1. 在 AppDelegate.swift 上实现回调方法:

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
       switch response.actionIdentifier {
          case "Accept":
          print("Clicked Accept")
          case "Reject":
          print("Clicked Reject")
          default:
       }
       completionHandler()
    }
    

当用户点击操作按钮时,将调用该回调方法。 该方法的执行必须执行与指定标识符相关联的任务,并运行completionHandler参数中的代码块。

添加定制 DeviceId 以进行注册

要发送 DeviceId,请使用 ENPushClientOptions 类的 setDeviceId 方法。

let options = ENPushClientOptions();
options.setDeviceId(deviceId: "YOUR_DEVICE_ID");

请记住为每个设备保留定制 DeviceId unique

启用富媒体通知

在 iOS 10 或更高版本上支持富媒体通知。 要接收富媒体通知,请实施UNNotificationServiceExtension。 该扩展将拦截并处理富媒体通知。

在服务扩展的didReceive() 方法中,添加以下代码以获取丰富的推送通知内容。

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
   self.contentHandler = contentHandler
   bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
   ENPushRichPushNotificationOptions.didReceive(request, withContentHandler: contentHandler)
}

向 iOS 设备发送通知

使用 发送通知 API 来发送 iOS 设备的推送通知。 您可以使用 NodeGo 管理 SDK,而不是直接调用 API。

发送通知{: caption="发送" caption-side="bottom"}

接收通知{: caption="接收通知接收" caption-side="bottom"}