首页 > 解决方案 > swift 4在后台自定义本地通知

问题描述

我已经编写了一些代码来在我的应用程序中实现自定义通知,但是当应用程序处于后台模式时这似乎不起作用这里是下面的代码:

let content = UNMutableNotificationContent()
        content.title = "test notifaction"
        content.body = "test notification after 5 second"
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
        let request  = UNNotificationRequest(identifier: "testidentifire", content: content, trigger: trigger)

应用内委托

//user notification method
    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.alert,.sound])
    }
    //response to user notification
    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        if response.notification.request.identifier == "testidentifire"
        {
            print("test")
        }
        completionHandler()
    }




    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

        UNUserNotificationCenter.current().delegate = self

        UNUserNotificationCenter.current().requestAuthorization(options: [.alert,.sound,.badge]) { (granted, error) in
            print("granted\(granted)")
        }
        return true
    }

现在,当我搜索时,我发现每个我无法理解我的代码有什么问题的地方都有相同的代码

标签: iosswiftnotifications

解决方案


在你看来试试这个确实加载它对我有用

 //sendign local notification you need three object a contant,trigger,represh
        let content = UNMutableNotificationContent()
        content.title = "test notifaction"
        content.body = "test notification after 5 second"
        content.sound = UNNotificationSound.default()

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: true)
        let request  = UNNotificationRequest(identifier: "testidentifire", content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            print("error\(error )")

        }

推荐阅读