在 iOS 中处理推送通知

improve this page | report issue


概述

可以使用 MobileFirst 提供的通知 API 来注册和注销设备以及预订和取消预订标记。 在本教程中,您将学会如何在使用 Swift 的 iOS 应用程序中处理推送通知。

有关静默通知或交互式通知的信息,请参阅:

先决条件:

跳转至:

通知配置

创建新的 Xcode 项目或使用现有项目。 如果该项目中还没有 MobileFirst 本机 iOS SDK,请遵循将 Mobile Foundation SDK 添加到 iOS 应用程序教程中的指示信息。

添加推送 SDK

  1. 打开该项目的现有 podfile,然后添加以下行:

    use_frameworks!
    
    platform :ios, 8.0
    target "Xcode-project-target" do
         pod 'IBMMobileFirstPlatformFoundation'
         pod 'IBMMobileFirstPlatformFoundationPush'
    end
    
    post_install do |installer|
         workDir = Dir.pwd
    
         installer.pods_project.targets.each do |target|
             debugXcconfigFilename = "#{workDir}/Pods/Target Support Files/#{target}/#{target}.debug.xcconfig"
             xcconfig = File.read(debugXcconfigFilename)
             newXcconfig = xcconfig.gsub(/HEADER_SEARCH_PATHS = .*/, "HEADER_SEARCH_PATHS = ")
             File.open(debugXcconfigFilename, "w") { |file| file << newXcconfig }
    
             releaseXcconfigFilename = "#{workDir}/Pods/Target Support Files/#{target}/#{target}.release.xcconfig"
             xcconfig = File.read(releaseXcconfigFilename)
             newXcconfig = xcconfig.gsub(/HEADER_SEARCH_PATHS = .*/, "HEADER_SEARCH_PATHS = ")
             File.open(releaseXcconfigFilename, "w") { |file| file << newXcconfig }
         end
    end
    
    • Xcode-project-target 替换为您的 Xcode 项目目标的名称。
  2. 保存并关闭该 podfile
  3. 命令行窗口中,浏览至该项目的根文件夹。
  4. 运行 pod install 命令。
  5. 通过 .xcworkspace 文件打开项目。

通知 API

MFPPush 实例

必须在一个 MFPPush 实例上发出所有 API 调用。 为此,需要在视图控制器中使用 var(例如,var push = MFPPush.sharedInstance();),然后在视图控制器中调用 push.methodName()

也可以针对要访问推送 API 方法的每个实例都调用 MFPPush.sharedInstance().methodName()

验证问题处理程序

如果 push.mobileclient 作用域映射到安全性检查,那么需要确保在使用任何推送 API 之前,存在已注册的匹配验证问题处理程序

凭证验证教程中了解有关验证问题处理程序的更多信息。

客户端

Swift 方法 描述
initialize() 针对提供的上下文,初始化 MFPPush。
isPushSupported() 设备是否支持推送通知。
registerDevice(completionHandler: ((WLResponse!, NSError!) -> Void)!) 向推送通知服务注册设备。
sendDeviceToken(deviceToken: NSData!) 将设备标记发送到服务器。
getTags(completionHandler: ((WLResponse!, NSError!) -> Void)!) 在推送通知服务实例中检索可用的标记。
subscribe(tagsArray: [AnyObject], completionHandler: ((WLResponse!, NSError!) -> Void)!) 使设备预订指定的标记。
getSubscriptions(completionHandler: ((WLResponse!, NSError!) -> Void)!) 检索设备当前预订的所有标记。
unsubscribe(tagsArray: [AnyObject], completionHandler: ((WLResponse!, NSError!) -> Void)!) 取消对特定标记的预订。
unregisterDevice(completionHandler: ((WLResponse!, NSError!) -> Void)!) 从推送通知服务注销设备。

初始化

客户机应用程序连接到 MFPPush 服务时,需要执行初始化。

  • 应先调用 initialize 方法,然后再使用任何其他 MFPPush API。
  • 它会注册回调函数以处理已收到的推送通知。
MFPPush.sharedInstance().initialize();

是否支持推送

检查设备是否支持推送通知。

let isPushSupported: Bool = MFPPush.sharedInstance().isPushSupported()

if isPushSupported {
    // Push is supported
} else {
    // Push is not supported
}

注册设备并发送设备标记

向推送通知服务注册设备。

MFPPush.sharedInstance().registerDevice(nil) { (response, error) -> Void in
    if error == nil {
        self.enableButtons()
        self.showAlert("Registered successfully")
        print(response?.description ?? "")
    } else {
        self.showAlert("Registrations failed.  Error \(error?.localizedDescription)")
        print(error?.localizedDescription ?? "")
    }
}
MFPPush.sharedInstance().sendDeviceToken(deviceToken)

注:通常在 didRegisterForRemoteNotificationsWithDeviceToken 方法的 AppDelegate 中调用此项。

获取标记

从推送通知服务检索所有可用标记。

MFPPush.sharedInstance().getTags { (response, error) -> Void in
    if error == nil {
        print("The response is: \(response)")
        print("The response text is \(response?.responseText)")
        if response?.availableTags().isEmpty == true {
            self.tagsArray = []
            self.showAlert("There are no available tags")
        } else {
            self.tagsArray = response!.availableTags() as! [String]
            self.showAlert(String(describing: self.tagsArray))
            print("Tags response: \(response)")
        }
    } else {
        self.showAlert("Error \(error?.localizedDescription)")
        print("Error \(error?.localizedDescription)")
    }
}

预订

预订所需的标记。

var tagsArray: [String] = ["Tag 1", "Tag 2"]

MFPPush.sharedInstance().subscribe(self.tagsArray) { (response, error)  -> Void in
    if error == nil {
        self.showAlert("Subscribed successfully")
        print("Subscribed successfully response: \(response)")
    } else {
        self.showAlert("Failed to subscribe")
        print("Error \(error?.localizedDescription)")
    }
}

获取预订

检索设备当前预订的标记。

MFPPush.sharedInstance().getSubscriptions { (response, error) -> Void in
   if error == nil {
       var tags = [String]()
       let json = (response?.responseJSON)! as [AnyHashable: Any]
       let subscriptions = json["subscriptions"] as? [[String: AnyObject]]
       for tag in subscriptions! {
           if let tagName = tag["tagName"] as? String {
               print("tagName: \(tagName)")
               tags.append(tagName)
           }
       }
       self.showAlert(String(describing: tags))
   } else {
       self.showAlert("Error \(error?.localizedDescription)")
       print("Error \(error?.localizedDescription)")
   }
}

取消预订

取消对标记的预订。

var tags: [String] = {"Tag 1", "Tag 2"};

// Unsubscribe from tags
MFPPush.sharedInstance().unsubscribe(self.tagsArray) { (response, error)  -> Void in
    if error == nil {
        self.showAlert("Unsubscribed successfully")
        print(String(describing: response?.description))
    } else {
        self.showAlert("Error \(error?.localizedDescription)")
        print("Error \(error?.localizedDescription)")
    }
}

注销

从推送通知服务实例注销设备。

MFPPush.sharedInstance().unregisterDevice { (response, error)  -> Void in
   if error == nil {
       // Disable buttons
       self.disableButtons()
       self.showAlert("Unregistered successfully")
       print("Subscribed successfully response: \(response)")
   } else {
       self.showAlert("Error \(error?.localizedDescription)")
       print("Error \(error?.localizedDescription)")
   }
}

处理推送通知

由本机 iOS 框架直接处理推送通知。 根据您的应用程序生命周期,iOS 框架将调用不同的方法。

例如,如果在运行应用程序时收到简单通知,那么将触发 AppDelegatedidReceiveRemoteNotification

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
    print("Received Notification in didReceiveRemoteNotification \(userInfo)")
    // display the alert body
      if let notification = userInfo["aps"] as? NSDictionary,
        let alert = notification["alert"] as? NSDictionary,
        let body = alert["body"] as? String {
          showAlert(body)
        }
}

从以下 Apple 文档中了解有关在 iOS 中处理通知的更多信息:http://bit.ly/1ESSGdQ

样本应用程序图像

样本应用程序

单击以下载 Xcode 项目。

用法样例

请查看样本的 README.md 文件以获取指示信息。

Inclusive terminology note: The Mobile First Platform team is making changes to support the IBM® initiative to replace racially biased and other discriminatory language in our code and content with more inclusive language. While IBM values the use of inclusive language, terms that are outside of IBM's direct influence are sometimes required for the sake of maintaining user understanding. As other industry leaders join IBM in embracing the use of inclusive language, IBM will continue to update the documentation to reflect those changes.
Last modified on June 01, 2020