IBM Cloud Mobile Services - Client SDK Swift Push
IBM Cloud Push Notifications 服务 提供了统一的推送服务,可以向移动和 Web 应用程序发送实时通知。该 SDK 允许 iOS 应用从服务接收推送通知。
在开始之前,请务必查阅 IBM Cloud Push Notifications 服务文档。
内容
必备条件
- iOS 8.0 或更高版本
- Xcode 8.0 或更高版本
- Swift 3.0 或更高版本
- Cocoapods 最新版本
- Carthage
安装
IBM Cloud Push Notifications iOS SDK 通过 Cocoapods 和 Carthage 提供。
Cocoapods
如果你的项目还没有 Podfile
,使用 pod init
命令创建一个。要使用 Cocoapods 安装 IBM Cloud Push Notifications iOS SDK,请将以下内容添加到你的 Podfile 中
use_frameworks!
target 'MyApp' do
platform :ios, '8.0'
pod 'BMSCore', '~> 2.0'
pod 'BMSPush', '~> 3.0'
end
从终端进入你的项目文件夹,并用 pod install
命令安装依赖。
对于使用 Swift 3.0 构建的应用,在 Xcode 8 (在安装 BMSCore 后)打开项目时,可能会收到提示 "将代码转换为当前 Swift 语法?",请不要转换 BMSPush,BMSCore 或 BMSAnalyticsAPI。
这将安装所需依赖,并创建一个新的 Xcode 工作空间。
注意:请始终打开新的 Xcode 工作空间,而不是原始的 Xcode 项目文件:MyApp.xcworkspace。
Carthage
要使用 Carthage 安装 BMSPush,请完成以下步骤
- 将其添加到你的 Cartfile 中
github "ibm-bluemix-mobile-services/bms-clientsdk-swift-push"
- 运行
carthage update
命令。 - 构建成功后,将
BMSPush.framework
、BMSCore.framework
和BMSAnalyticsAPI.framework
添加到你的 Xcode 项目中。
要完成集成,请遵循此处的说明。
Xcode 8
选择以下任一选项
- 对于
Swift 3.+
应用, 使用carthage update
。
初始化 SDK
按照以下步骤启用 iOS 应用接收通知的能力。
-
在您的
.swift
文件中添加import
语句。import BMSCore import BMSPush
-
初始化 Core SDK 和 Push SDK
BMSClient.sharedInstance.initialize(bluemixRegion: "Location where your app Hosted") BMSPushClient.sharedInstance.initializeWithAppGUID(appGUID: "your push appGUID", clientSecret:"your push client secret")
其中 bluemixRegion
指定了应用程序托管的位置。您可以使用以下值
BMSClient.Region.usSouth
BMSClient.Region.unitedKingdom
BMSClient.Region.sydney
BMSClient.Region.germany
BMSClient.Region.jpTok
BMSClient.Region.usEast
appGUID
是 Push 服务实例的 Id 值,而 clientSecret
是 Push 服务实例客户端机密值。
注意:如果您正在使用 Xcode8 公测版,请添加
yourApp.entitlements
。为此,请转到 Targets > Capabilities 并启用推送通知功能。
注册通知
初始化成功后,Apple 推送通知服务 (APNs) 将在 didRegisterForRemoteNotificationsWithDeviceToken
方法中提供一个令牌。将令牌传递到 Push 通知服务注册 API。
以下选项是受支持的
-
无需UserId进行注册
要使用 userId 进行注册,请使用以下模式
func application (_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){ BMSPushClient.sharedInstance.registerWithDeviceToken(deviceToken: deviceToken) { (response, statusCode, error) -> Void in if error.isEmpty { print( "Response during device registration: \(response) and status code is:\(statusCode)") } else { print( "Error during device registration: \(error) and status code is: \(statusCode)") } }
-
使用UserId进行注册
在将设备与 Push 通知服务注册时,可以指定
userId
。注册方法将接受一个额外的参数 -userId
func application (_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data){ BMSPushClient.sharedInstance.registerWithDeviceToken(deviceToken: deviceToken, WithUserId: "your userId") { (response, statusCode, error) -> Void in if error.isEmpty { print( "Response during device registration : \(response) and status code is:\(statusCode)") } else { print( "Error during device registration \(error) and status code is:\(statusCode) ") } }
其中
WithUserId
是您希望将设备注册到 Push 服务实例的用户标识值。注意:如果提供了 userId,则在初始化期间必须提供客户端机密值。
-
从通知中注销设备
使用以下代码片段从 Push 通知服务实例注销设备
BMSPushClient.sharedInstance.unregisterDevice(completionHandler: { (response, statusCode, error) -> Void in if error.isEmpty { print( "Response during unregistering device : \(response) and status code is:\(statusCode)") } else { print( "Error during unregistering device \(error) and status code is:\(statusCode)") } }
注意:要从基于 userId 的注册中注销,您必须调用注册方法 不带 userId。
Push 通知服务标签
获取标签
retrieveAvailableTagsWithCompletionHandler
API 返回设备可订阅的标签列表。设备订阅特定的标签后,可以接收为该标签发送的通知。
将以下代码片段添加到您的 Swift 移动应用程序中,以获取设备可以订阅的标签列表。
BMSPushClient.sharedInstance.retrieveAvailableTagsWithCompletionHandler(completionHandler: { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during retrieve tags : \(response) and status code is:\(statusCode)")
} else {
print( "Error during retrieve tags \n - status code: \(statusCode) \n Error :\(error) \n")
}
}
订阅标签
subscribeToTags
API 将订阅 iOS 设备的指定标签列表。设备订阅特定的标签后,可以接收任何为该标签发送的推送通知。
将以下代码片段添加到您的 Swift 移动应用程序中,以订阅标签列表。
BMSPushClient.sharedInstance.subscribeToTags(tagsArray: response!, completionHandler: { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during Subscribing to tags : \(response?.description) and status code is:\(statusCode)")
} else {
print( "Error during subscribing tags \n - status code: \(statusCode) \n Error :\(error) \n")
}
}
获取已订阅标签
retrieveSubscriptionsWithCompletionHandler
API 将返回设备已订阅的标签列表。
将以下代码片段添加到您的 Swift 移动应用程序中,以获取订阅列表。
BMSPushClient.sharedInstance.retrieveSubscriptionsWithCompletionHandler(completionHandler: { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during retrieving subscribed tags : \(response?.description) and status code is:\(statusCode)")
} else {
print( "Error during retrieving subscribed tags \n - status code: \(statusCode) \n Error :\(error) \n")
}
}
取消订阅标签
unsubscribeFromTags
API 将从标签列表中移除设备的订阅。
使用以下代码片段从标签中取消订阅。
BMSPushClient.sharedInstance.unsubscribeFromTags(tagsArray: response!, completionHandler: { (response, statusCode, error) -> Void in
if error.isEmpty {
print( "Response during unsubscribed tags : \(response?.description) and status code is:\(statusCode)")
} else {
print( "Error during unsubscribed tags \(error)and status code is:\(statusCode)")
}
}
在 iOS 设备上接收推送通知
要在 iOS 设备上接收推送通知,请将以下 Swift 方法添加到应用程序的 appDelegate.swift
文件中
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//UserInfo dictionary will contain data sent from the server
}
通知选项
静默通知
静默通知不会出现在设备屏幕上。这些通知在应用后台接收,应用会唤醒至多30秒以执行指定的后台任务。用户可能不会意识到通知的到来。
要处理静默推送通知,请使用 didReceiveRemoteNotification_fetchCompletionHandler
方法。
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let contentAPS = userInfo["aps"] as [NSObject : AnyObject]
if let contentAvailable = contentAPS["content-available"] as? Int {
//silent or mixed push
if contentAvailable == 1 {
completionHandler(UIBackgroundFetchResult.NewData)
} else {
completionHandler(UIBackgroundFetchResult.NoData)
}
} else {
//Default notification
completionHandler(UIBackgroundFetchResult.NoData)
}
}
交互式通知
要启用交互式推送通知,必须在初始化期间传递通知操作对象。以下是一个启用交互式通知的示例代码
let acceptButton = BMSPushNotificationAction(identifierName: "Accept", buttonTitle: "Accept", isAuthenticationRequired: false, defineActivationMode: UIUserNotificationActivationMode.background)
let rejectButton = BMSPushNotificationAction(identifierName: "Reject", buttonTitle: "Reject", isAuthenticationRequired: false, defineActivationMode: UIUserNotificationActivationMode.background)
let category = BMSPushNotificationActionCategory(identifierName: "category", buttonActions: [acceptButton, rejectButton])
let notificationOptions = BMSPushClientOptions()
notificationOptions.setInteractiveNotificationCategories(categoryName: [category])
BMSPushClient.sharedInstance.initializeWithAppGUID(appGUID: "your push appGUID", clientSecret:"your push client secret", options: notificationOptions)
处理交互式推送通知
在 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
要发送 Device Identifier
,请使用 BMSPushClientOptions
的 setDeviceId
方法。
let notificationOptions = BMSPushClientOptions()
notificationOptions.setDeviceId(deviceId: "YOUR_DEVICE_ID")
注意:请确保为每个设备保持自定义 Device Identifier 的 唯一性。
启用富媒体通知
富媒体通知支持在iOS 10或更高版本。要接收富媒体通知,实现UNNotificationServiceExtension
。该扩展将拦截并处理富媒体通知。
在服务扩展的didReceive()
方法中,添加以下代码来检索富推送通知内容。
override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
self.contentHandler = contentHandler
bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
BMSPushRichPushNotificationOptions.didReceive(request, withContentHandler: contentHandler)
}
高级选项
iOS徽标
对于iOS设备,这是显示在应用图标上的徽标数字。如果此属性不存在,则徽标将不会被改变。要移除徽标,将此属性的值设置为0。
自定义声音
将声音文件添加到您的iOS应用程序中。
启用监控
要查看iOS的通知监控状态,您必须添加以下代码片段
//Send notification status when app is opened by clicking notifications
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
let push = BMSPushClient.sharedInstance
let respJson = (userInfo as NSDictionary).value(forKey: "payload") as! String
let data = respJson.data(using: String.Encoding.utf8)
let jsonResponse:NSDictionary = try! JSONSerialization.jsonObject(with: data! , options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
let messageId:String = jsonResponse.value(forKey: "nid") as! String
push.sendMessageDeliveryStatus(messageId: messageId) { (res, ss, ee) in
print("Send message status to the Push server")
}
}
// Send notification status when the app is in background mode
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
let payLoad = ((((userInfo as NSDictionary).value(forKey: "aps") as! NSDictionary).value(forKey: "alert") as! NSDictionary).value(forKey: "body") as! NSString)
self.showAlert(title: "Recieved Push notifications", message: payLoad)
let push = BMSPushClient.sharedInstance
let respJson = (userInfo as NSDictionary).value(forKey: "payload") as! String
let data = respJson.data(using: String.Encoding.utf8)
let jsonResponse:NSDictionary = try! JSONSerialization.jsonObject(with: data! , options: JSONSerialization.ReadingOptions.allowFragments) as! NSDictionary
let messageId:String = jsonResponse.value(forKey: "nid") as! String
push.sendMessageDeliveryStatus(messageId: messageId) { (res, ss, ee) in
completionHandler(UIBackgroundFetchResult.newData)
}
}
注意:当应用处于后台时,要获取消息状态,您必须发送
MIXED
或SILENT
推送通知。如果应用被强制退出,将不会收到消息送达状态。
通过点击推送通知打开网址
要点击推送通知打开网址,你可以在负载中发送一个url
字段。
{
"message": {
"alert": "Notification alert message",
"url":"https://console.ng.bliuemix.net"
}
}
在你的应用中,进入AppDelegate
文件,在didFinishLaunchingWithOptions
中检查url
的值。
let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary
if remoteNotif != nil {
let urlField = (remoteNotif?.value(forKey: "url") as! String)
application.open(URL(string: urlField)!, options: [:], completionHandler: nil)
}
参数化推送通知
要启用IBM Cloud推送通知的参数化,请按照以下步骤操作:
- 在
BMSPushClientOptions
中添加变量的键值对
let variables = [
"username":"testname",
"accountNumber":"3564758697057869"
]
let notifOptions = BMSPushClientOptions()
notifOptions.setPushVariables(pushVaribales: variables)
-
将
BMSPushClientOptions
传递到initializeWithAppGUID()
方法中。在注册设备时,IBM Cloud推送通知iOS SDK会将这些变量传递到IBM Cloud推送通知服务。 -
在
application:didReceiveRemoteNotification:fetchCompletionHandler ()
中添加以下内容以处理基于模板的推送通知:let push = BMSPushClient.sharedInstance push.didReciveBMSPushNotification(userInfo: userInfo) { (res, error) in completionHandler(UIBackgroundFetchResult.newData) }
-
发送推送通知时,在
"{{}}"
中添加变量键
{
"message": {
"alert": "hello {{username}} , balance on your account {{accountNumber}} is $1200"
}
}
注意:如果应用被强制杀死,基于模板的推送通知可能不会显示在设备上。
API文档
在此处找到API文档 - http://ibm-bluemix-mobile-services.github.io/API-docs/client-SDK/BMSPush/Swift/index.html
示例和视频
-
有关示例,请访问 - GitHub示例
-
有关视频教程,请访问 - IBM Cloud推送通知
了解更多
与 IBM Cloud 连接
Twitter | YouTube | 博客 | Facebook |
© 2020-21 IBM 公司版权所有。
遵照 Apache 许可证 2.0 版(“许可证”);除非遵守许可证规定,否则不得使用此文件。您可以在以下位置获取许可证副本:
https://apache.ac.cn/licenses/LICENSE-2.0
除非适用法律法规或书面同意,否则在许可证下分发的软件按“原样”提供,不包括任何明示或暗示的保证或条件。有关许可证规定的权限和限制,请参阅许可证。