IOS版本中的本地和推送通知兼容

时间:2017-03-09 07:02:52

标签: ios swift apple-push-notifications uilocalnotification

我在local Notifications中开发了iOS 10。它工作得很好。但是现在如果用户使用local notifications及以上版本,我应该如何编码push notificationiOS 9。有人可以帮忙吗?

以下是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)
        }

     }

 }

2 个答案:

答案 0 :(得分:45)

IOS 12 : - 群组通知

设置threadIdentifier UNMutableNotificationContent以创建群组通知

创建本地通知组

let content = UNMutableNotificationContent()
content.title = "Group Notifications"
content.body = "Body of notification"
content.threadIdentifier = "group-identifire"

创建远程通知组需要在有效负载中传递thread-id

{
 "aps" : {
     "alert" : {
         "title" : "Group Notifications",
         "body" : "Body of notification"
     }
     "thread-id" : "group-identifire"
 }
}

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

创建通知请求

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及以上版本

仅当应用程序位于前台

时,才会在委托上调用该方法

您可以通过以下方法提供默认横幅

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

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

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

}

答案 1 :(得分:11)

我为 Swift 3 创建了这个类,它具有请求推送通知权限和发送通知的功能。 适用于iOS 9和iOS 10 +。

import UIKit
import UserNotifications

class LocalNotification: NSObject, UNUserNotificationCenterDelegate {

    class func registerForLocalNotification(on application:UIApplication) {
        if (UIApplication.instancesRespond(to: #selector(UIApplication.registerUserNotificationSettings(_:)))) {
            let notificationCategory:UIMutableUserNotificationCategory = UIMutableUserNotificationCategory()
            notificationCategory.identifier = "NOTIFICATION_CATEGORY"

            //registerting for the notification.
            application.registerUserNotificationSettings(UIUserNotificationSettings(types:[.sound, .alert, .badge], categories: nil))
        }
    }

    class func dispatchlocalNotification(with title: String, body: String, userInfo: [AnyHashable: Any]? = nil, at date:Date) {

        if #available(iOS 10.0, *) {

            let center = UNUserNotificationCenter.current()
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.categoryIdentifier = "Fechou"

            if let info = userInfo {
                content.userInfo = info
            }

            content.sound = UNNotificationSound.default()

            let comp = Calendar.current.dateComponents([.hour, .minute], from: date)

            let trigger = UNCalendarNotificationTrigger(dateMatching: comp, repeats: true)

            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

            center.add(request)

        } else {

            let notification = UILocalNotification()
            notification.fireDate = date
            notification.alertTitle = title
            notification.alertBody = body

            if let info = userInfo {
                notification.userInfo = info
            }

            notification.soundName = UILocalNotificationDefaultSoundName
            UIApplication.shared.scheduleLocalNotification(notification)

        }

        print("WILL DISPATCH LOCAL NOTIFICATION AT ", date)

    }
}

<强>用法:

您可以在任何地方请求权限:

LocalNotification.registerForLocalNotification(on: UIApplication.shared)

并发送本地通知:

LocalNotification.dispatchlocalNotification(with: "Notification Title for iOS10+", body: "This is the notification body, works on all versions", at: Date().addedBy(minutes: 2))

提示

您可以将通知设置为在将来的任何日期触发,在此示例中,我使用日期扩展名来获取通知触发的未来日期(以分钟为单位)。就是这样:

extension Date {
    func addedBy(minutes:Int) -> Date {
        return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
    }
}