如何在swift中处理推送通知?

vjrehmav  于 2023-02-03  发布在  Swift
关注(0)|答案(3)|浏览(207)

我有一个ios应用程序,我发送推使用apns。我需要处理推消息,如果它是正确的显示消息。我怎样才能实现它在swift?这是我的代码:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions:
    [NSObject: AnyObject]?) -> Bool {
    registerForPushNotifications(application)
    return true
}

func registerForPushNotifications(application: UIApplication) {
    let notificationSettings = UIUserNotificationSettings(
        forTypes: [.Badge, .Sound, .Alert], categories: nil)
    application.registerUserNotificationSettings(notificationSettings)
}

func application(application: UIApplication, didRegisterUserNotificationSettings notificationSettings: UIUserNotificationSettings) {
    if notificationSettings.types != .None {
        application.registerForRemoteNotifications()
    }
}

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
    let tokenChars = UnsafePointer<CChar>(deviceToken.bytes)
    var tokenString = ""

    for i in 0..<deviceToken.length {
        tokenString += String(format: "%02.2hhx", arguments: [tokenChars[i]])
    }

    print("Device Token:", tokenString)
}

func application(application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: NSError) {
    print("Failed to register:", error)
}

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {


}

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) {

}

func applicationDidBecomeActive(application: UIApplication) {
    UIApplication.sharedApplication().applicationIconBadgeNumber = 0
}

在什么功能中我可以处理推送通知?

72qzrwbm

72qzrwbm1#

要处理推送通知时,到达您的iOS应用程序是棘手的一部分,以充分利用它们。
当推送通知到达时,您的应用程序可以处于

    • 关闭状态-应用程序被终止,运行状态-应用程序在前台,挂起状态-应用程序在后台**,

到达时处理推送通知
让我们逐一讨论如何在每种状态下处理它们

    • 关闭状态:**

当应用程序关闭时(其他应用程序正在运行或手机锁定),推送通知到达,您点击它打开应用程序。控制权将交给appDelegate’s方法,即didFinishLaunchingWithOptions:请注意,当您正常启动应用程序通过点击其图标从您的手机. didFinishLaunchingWithOptions:调用第一个与其launchOptions == nil.如果您启动应用程序通过点击收到的推送通知didFinishLaunchingWithOptions:下面是要点如果你想在应用程序点击推送通知启动时做一些特殊的事情,你需要在你的didFinishLaunchingWithOptions中添加代码:
像这样

if (launchOptions != nil)
{
   //do some thing special e.g. display particular ViewController or Set some notification badge value.
}
    • 运行状态**

如果您的应用程序正在运行(前台)并且收到推送通知,则屏幕上不会显示与该通知相关的任何内容-无警报、无消息、无声音。相反,将调用appDelegate的以下方法

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}

您可以根据自己的需要实现此方法,即如何响应通知。

    • 挂起状态**

如果您的应用程序在后台(手机被锁定或其他应用程序正在运行),并收到推送通知,通知将显示声音,并单击该通知应用程序将启动以下方法调用appDelegate

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
}

这与在运行状态下收到通知时调用的方法相同。请注意,您始终可以使用UIApplication的applicationState属性在此方法中查找您的应用是否从后台状态唤醒。在这种情况下,您可以在通过推送通知从后台打开应用时执行一些特殊操作。

t40tm48m

t40tm48m2#

根据你的问题
一旦在设备上收到通知,您无法切换通知的可见性。
这种特性/功能只有在Android上才能实现。在收到通知时,Android开发人员可以决定是否呈现视图。
所以试着从服务器端控制它。

webghufk

webghufk3#

我想举一个处理远程推送通知的例子。
所有文件都将保存在AppDelegate.swift文件中;
首先从这个功能注册后获得您的令牌,可以从您的服务器或提供商发送远程推送通知(RPM):

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    
    // Send device token that accepted to retrieve remote notifications to server
    let token = deviceToken.map { String(format: "%02.2hhx", $0) }.joined()
    NSLog("APNs registration success, device token: \(token)")
}

检查didFinishLaunchWithOptions方法内的启动选项中是否存在远程通知信息,以了解是否通过点击如下通知警报启动了应用程序:

// Check if there any user info about remote notifications in 'launchOptions'
        /// Get user your data from userInfo dictionary if you need
    if let userInfo = launchOptions?[.remoteNotification] as? [String: AnyObject],
          let exmplValue = userInfo["yourValue"] as? String {
        NSLog("[AppDelegate] - Info: App launched by tapping notification alert. We have new value: \(exmplValue)")
       /// Here you can change rootVC or storing some values to process it in your mainVC etc.
    }

然后实现didReceiveRemoteNotification函数,如下所示,以处理处于活动和非活动状态的推送通知:

/// This function made for handling push notifications when app running (both states active or inactive)
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    
    /// Hide badge number if it exist
    application.applicationIconBadgeNumber = 0
    
    /// Get user your data from userInfo dictionary if you need
    guard let aps = userInfo["aps"] as? [String: Any],
          let alert = aps["alert"] as? [String: Any],
          let title = alert["title"] as? String,
          let body = alert["body"] as? String,
          let exampleValue = userInfo["example"] as? String else {
        NSLog("[AppDelegate] - Warning: user info missing aps or other data.")
        return
    }
    
   /// Check current application state
   if UIApplication.shared.applicationState == .active {
      // Your app in foreground, you can ask user to want to take action about what you want to do.
   } else {
      // Your app in background at most in inactive mode, user when taps on notification alert app will become active so you can do whatever you want directly
   }
}
    • 奖金:**

在AppDelegate.swift文件中实现UNUserNotificationCenterDelegate,然后在didFinishLaunchWithOptions中确认通知中心的委托,如下所示:UNUserNotificationCenter.current().delegate = self最后覆盖此功能以调整徽章、声音、将呈现的通知警报。

// Assign delegate to show LPN or RPN badge, alert, sound
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

    /// I would like to notify user by sound only when app is active
    /// otherwise show notification (alert, badge, sound)
    if UIApplication.shared.applicationState == .active {
        completionHandler(.sound)
    } else {
        completionHandler([.alert, .badge, .sound])
    }
    
}

请记住,在这些示例中,我没有实现silent(背景)通知,因为当我激活静音通知我的应用程序处理以下功能内的所有类型的通知,我无法理解我的应用程序通过点击RPM或其他东西启动,我暂时不熟悉这种情况,因此如果需要,您必须添加后台模式功能,并在您的目标-〉您的应用程序-〉中选中远程通知签名和能力,然后执行此函数来处理RPM:

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

快乐编码

相关问题