IOS版本中的本地和推送通知兼容 [英] Local and Push Notifications in IOS version compatible

查看:108
本文介绍了IOS版本中的本地和推送通知兼容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 iOS 10 中开发了本地通知。它工作得很好。但是现在如何编码本地通知推送通知如果用户使用 iOS 9 及以上版本。有人可以帮忙吗?

I developed local Notifications in iOS 10. It is working perfectly. But now how should i code local notifications and push notification if user is using iOS 9 and above versions. Can anyone help please?

以下是 iOS 10中的代码

import UIKit
import UserNotifications

@available(iOS 10.0, *)
class ViewController: UIViewController,UNUserNotificationCenterDelegate {
    override func viewDidLoad() {
       super.viewDidLoad()

       if #available(iOS 10.0, *) {
        //Seeking permission of the user to display app notifications
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge], completionHandler: {didAllow,Error in })
        UNUserNotificationCenter.current().delegate = self

       }
   }

   //To display notifications when app is running  inforeground
   func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
       completionHandler([.alert, .sound, .badge])
   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
       // Dispose of any resources that can be recreated.
   }

   @IBAction func buttonPressed(_ sender: UIButton) {

       if #available(iOS 10.0, *) {

           //Setting content of the notification
           let content = UNMutableNotificationContent()
           content.title = "hello"
           content.body = "notification pooped out"
           content.badge = 1

           //Setting time for notification trigger
           let date = Date(timeIntervalSinceNow: 10)
           var dateCompenents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)

           let trigger = UNCalendarNotificationTrigger(dateMatching: dateCompenents, repeats: false)
           //Adding Request
           let request = UNNotificationRequest(identifier: "timerdone", content: content, trigger: trigger)
           UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
        }

     }

 }


推荐答案

IOS 11 : - 您还可以在iOS 11中使用以下代码。推送和本地通知不需要任何更改

IOS 11 :- You can also use following code for iOS 11. No any kind of changes requires in push and local notification

正在创建通知请求

import UserNotifications

if #available(iOS 10.0, *) {
    //iOS 10.0 and greater
    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: { granted, error in
        DispatchQueue.main.async {
            if granted {
                UIApplication.shared.registerForRemoteNotifications()
            }
            else {
                //Do stuff if unsuccessful...
            }
        }
   })
}
else { 
    //iOS 9
    let type: UIUserNotificationType = [UIUserNotificationType.badge, UIUserNotificationType.alert, UIUserNotificationType.sound]
    let setting = UIUserNotificationSettings(types: type, categories: nil)
    UIApplication.shared.registerUserNotificationSettings(setting)
    UIApplication.shared.registerForRemoteNotifications()
}

安排本地通知

if #available(iOS 10.0, *) {
    //iOS 10 or above version
    let center = UNUserNotificationCenter.current()
    let content = UNMutableNotificationContent()
    content.title = "Late wake up call"
    content.body = "The early bird catches the worm, but the second mouse gets the cheese."
    content.categoryIdentifier = "alarm"
    content.userInfo = ["customData": "fizzbuzz"]
    content.sound = UNNotificationSound.default()

    var dateComponents = DateComponents()
    dateComponents.hour = 15
    dateComponents.minute = 49
    let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)

    let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
    center.add(request)
} else {
    // ios 9 
    let notification = UILocalNotification()
    notification.fireDate = NSDate(timeIntervalSinceNow: 5) as Date
    notification.alertBody = "Hey you! Yeah you! Swipe to unlock!"
    notification.alertAction = "be awesome!"
    notification.soundName = UILocalNotificationDefaultSoundName
    UIApplication.shared.scheduleLocalNotification(notification)
}

UIApplicationDelegate

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    print(token)
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {

}

UNUserNotificationCenterDelegate

仅适用于ios 10及以上版本

Only available in ios 10 and above version

仅当应用程序位于前台时才会在委托上调用该方法

The method will be called on the delegate only if the application is in the foreground

您可以使用以下方法显示默认横幅

You can present default banner with helping of following method

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    completionHandler([.badge,.alert,.sound])
}

该方法将在。上调用当用户通过打开应用程序,解除通知或选择UNNotificationAction

The method will be called on the delegate when the user responded to the notification by opening the application, dismissing the notification or choosing a UNNotificationAction

@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

}

这篇关于IOS版本中的本地和推送通知兼容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆