本地通知已排定,但未在挂起和运行模式下传递

时间:2019-04-10 10:22:12

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

我想在无提示远程通知到达时(内容可用: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 ]

2 个答案:

答案 0 :(得分:2)

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

使用此

答案 1 :(得分:0)

// AppDelegate

UNUserNotificationCenter.current().delegate = self
let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound]
        UNUserNotificationCenter.current().requestAuthorization(
            options: authOptions,
            completionHandler: {_, _ in })


application.registerUserNotificationSettings(UIUserNotificationSettings(types: [.alert, .badge, .sound], categories: nil))

//在ViewController中

 let content = UNMutableNotificationContent()
        content.title = “Notification Title”
        content.body = “Notification Body”
        content.sound = UNNotificationSound.default()
        content.badge = 1

        let date = Date()

        let localDate = date.toLocalTime()

        var triggerDaily = Calendar.current.dateComponents([.hour,.minute,.second,], from: localDate)
        triggerDaily.hour = 22
        triggerDaily.minute = 00
        triggerDaily.second = 00

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

        let identifier = "Local Notification"
        let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)

        UNUserNotificationCenter.current().add(request) { (error) in
            if let error = error {
                print("Error \(error.localizedDescription)")
            }
        }

//添加扩展名以转换时间

extension Date { 

  func convertToGlobalTime() -> Date {
     let currentTimezone = TimeZone.current
     let interval = -TimeInterval(currentTimezone.secondsFromGMT(for: self))
     return Date(timeInterval: interval, since: self)
 }

 func convertToLocalTime() -> Date {
     let currentTimezone = TimeZone.current
     let interval = TimeInterval(currentTimezone(for: self))
     return Date(timeInterval: interval, since: self)
 }

}