推送Swift iOS 10的通知

时间:2016-10-26 15:24:28

标签: ios swift push-notification notifications ios10

我很难获得推送通知,以便在iOS 10中使用Swift。注册似乎已成功完成,但创建通知会在设备上执行任何操作并返回nil错误。我缺少什么想法?

import Foundation
import UIKit
import UserNotifications
class SPKPushNotifications
{
    class func register(application:UIApplication){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.badge, .alert, .sound]) { (granted, error) in
                // Enable or disable features based on authorization.
                application.registerForRemoteNotifications()
            }
        } else {
            let notificationTypes: UIUserNotificationType = [UIUserNotificationType.alert, UIUserNotificationType.badge, UIUserNotificationType.sound]
            let pushNotificationSettings = UIUserNotificationSettings(types: notificationTypes, categories: nil)
            application.registerUserNotificationSettings(pushNotificationSettings)
            application.registerForRemoteNotifications()
        }
    }
    class func unregister(application:UIApplication){
        application.unregisterForRemoteNotifications()
    }
    class func create(title:String, body:String, delay:Double, repeats:Bool){
        if #available(iOS 10.0, *) {
            let content = UNMutableNotificationContent()
            content.title = title
            content.body = body
            content.sound = UNNotificationSound.default() //idk if we're gonna want something else
            content.badge = NSNumber(value:UIApplication.shared.applicationIconBadgeNumber+1)
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval:delay, repeats:repeats)
            let request = UNNotificationRequest(identifier:title, content:content, trigger:trigger)
            let center = UNUserNotificationCenter.current()
            center.add(request){ (error) in
                print(error)
            }

        } else {
            // Fallback on earlier versions
        }
    }
    class func delete(){
        if #available(iOS 10.0, *) {
            let center = UNUserNotificationCenter.current()
            center.removeAllDeliveredNotifications()
        } else {
            // Fallback on earlier versions
        }
    }
}

1 个答案:

答案 0 :(得分:0)

如果应用程序位于前台,您将看不到通知。当应用程序在后台时,尝试将请求添加到通知中心。

您可以(仅限此测试)通过添加几秒钟睡眠并将应用程序移至后台。或者将通知安排在应用程序未在前台运行的较晚时间。