【问题标题】:Notification comes only when the app is closed [duplicate]仅当应用程序关闭时才会发出通知[重复]
【发布时间】:2021-10-27 23:19:08
【问题描述】:

我想在我的应用上安排每日通知。但问题是当应用程序打开时通知不会出现,只有当我退出应用程序时才会出现通知。

注意:我是ios开发的初学者

我的功能:

func sheduleDailyLocalNotification() {
    
    let calendar = Calendar.current
    let hour = calendar.component(.hour, from: currentDate)
    let minute = calendar.component(.minute, from: currentDate)

    
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
        
        if success {
            
            let content = UNMutableNotificationContent()
            content.title = "iGrow Goals"
            content.subtitle = "Don't forget to check your today's goal steps"
            content.sound = UNNotificationSound.default
            
            // Configure the recurring date.
            var dateComponents = DateComponents()
            dateComponents.calendar = Calendar.current
            
            dateComponents.hour = hour
            dateComponents.minute = minute
            
            let trigger = UNCalendarNotificationTrigger(
                dateMatching: dateComponents, repeats: false)
            
            // choose a random identifier
            let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
            
            // add our notification request
            UNUserNotificationCenter.current().add(request)
                            
        }else if let error = error {
            print(error.localizedDescription)
        }
        
    }
    
    
}

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    像这样设置 UNUserNotificationCenter 委托(在您的应用生命周期的早期):

    let userNotificationCenter = UNUserNotificationCenter.current()
    userNotificationCenter.delegate = self
    // delegate must adopt UNUserNotificationCenterDelegate protocol
    

    然后在 UNUserNotificationCenter 委托中实现这个方法:

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        completionHandler([.badge, .alert, .sound]) // Insert in the returned array what the app should handle
    }
    

    如果在您的应用处于前台时触发通知,则假定您的应用会处理它(可能使用自定义行为和界面),但实现上述方法可以触发默认行为。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-10
      相关资源
      最近更新 更多