ios - 本地通知已安排,但不会以暂停和非运行模式发送

标签 ios swift apple-push-notifications background-fetch

我想为我的应用程序添加后台获取,当静默远程通知到达时(content-available : 1 ),所以当它到达时,我在本地触发后台更新,检查新数据,如果是,则生成本地为用户推送通知。但是,只有当应用程序处于后台、未挂起或未运行状态时,它才能完美运行。在这些状态下,我得到它来获取一些数据,但没有触发本地通知(它是在设备的控制台中创建的),有什么办法可以解决这个问题吗?

这是我生成推送的代码(它按预期工作)

func generatePushNotification(with title: String, body: String, badge: Int = 1){
        let content = UNMutableNotificationContent()
        content.badge = badge as NSNumber
        content.title = title
        content.body = body
        content.sound = UNNotificationSound.default
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1,
                                                        repeats: false)
        let notification = UNNotificationRequest(identifier: "pushLocal", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(notification) { (error) in
            if error != nil {
                NSLog((error?.localizedDescription)!)
            }
        }
    }

这是我的 notificationFetch 代码

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        networkManager.getScheduleForGroup(group) { (resp, error) in
            self.generatePushNotification(with: "Back", body: "ground")
            completionHandler(.newData)

        }
        completionHandler(.noData)

    }

这是控制台输出:

dasd    CANCELED: com.apple.pushLaunch.**:297454 <private>!

SpringBoard    Saving notification 802A-AE8C: 0 [ hasAlertContent: 0, shouldPresentAlert: 1 ]

SpringBoard  Delivered user visible push notification 802A-AE8C

SpringBoard  Load 0 pending notification dictionaries

SpringBoard  Adding notification 802A-AE8C to destinations 0 [ hasAlertContent: 0, shouldPresentAlert: 1 hasSound: 0 shouldPlaySound: 1 ]

最佳答案

let content = UNMutableNotificationContent()
content.title = title
content.body = body
content.sound = UNNotificationSound.default()

var dateComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: Date())

let trigger = UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: false)

let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

UNUserNotificationCenter.current().add(request, withCompletionHandler: { (error) in
    if let error = error{
        print(error)
    }
})
UNUserNotificationCenter.current().delegate = self

使用这个

关于ios - 本地通知已安排,但不会以暂停和非运行模式发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55610162/

相关文章:

objective-c - 使用自定义表格 View 单元格中的按钮

iOS:在多任务处理中检测 Regular 或 Compact

swift - 测试实例是否是 Swift 中带有类型别名的协议(protocol)?

iOS - 要求在初始拒绝后启用推送通知

objective-c - 检查对象实例的属性是否为 'blank'

ios - 如何修复弃用警告消息?

快速检查 NSDate 不为零

android - 如何将我的 Android 代码转换为我的 Firebase 函数的 Swift 代码?

ios - 远程删除以前发送的通知

apple-push-notifications - 在 Swift2 中通过 HTTP2 与 APNS 服务器通信