【问题标题】:how to fire local notification on time in swift?如何在 swift 中按时触发本地通知?
【发布时间】:2025-11-26 06:45:01
【问题描述】:

目前我正在 swift 5 中开展一个项目。我正在尝试在特定日期和时间推送本地通知。我已经尝试过下面的代码,当我设置 60.0 间隔时,它的工作发现但是当我设置特定的日期和时间时,它不起作用。

我已经搜索并检查了很多问题,但仍然没有找到解决方案。我检查了以下问题

get current date from [NSDate date] but set the time to 10:00 am

UNUserNotificationCenter Swift - Local Notification Not Firing in specific cases


      let app = UIApplication.shared


      let notificationSettings = UIUserNotificationSettings(types: [.alert, .sound], categories: nil)
      app.registerUserNotificationSettings(notificationSettings)
      let calendar = NSCalendar.current

      let date = NSDateComponents()
      print("before date get ::=> \(date)")
      date.hour = 16
      date.minute = 52
      date.month = 6
      date.day = 20
      date.year = 2019
      date.timeZone = NSTimeZone.system
      print("after custom date get ::=> \(date)")


      let alarm = UILocalNotification()
      alarm.fireDate = calendar.date(from: date as DateComponents)
      alarm.timeZone = NSTimeZone.default
      alarm.alertTitle = "Data success"
      alarm.alertBody = "successfuly"
      alarm.soundName = "Sound.wav"
      app.scheduleLocalNotification(alarm)
      app.scheduleLocalNotification(alarm)

      let content = UNMutableNotificationContent()
      content.title = NSString.localizedUserNotificationString(forKey: "Elon said:", arguments: nil)
      content.body = NSString.localizedUserNotificationString(forKey: "Hello Tom!Get up, let's play with Jerry!", arguments: nil)
      content.sound = UNNotificationSound.default
      content.badge = UIApplication.shared.applicationIconBadgeNumber + 1 as NSNumber;
      content.categoryIdentifier = "com.elonchan.localNotification"
      // Deliver the notification in 60 seconds.
      let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 60.0 , repeats: false)
      let request = UNNotificationRequest.init(identifier: "FiveSecond", content: content, trigger: trigger)
      // Schedule the notification.
      let center = UNUserNotificationCenter.current()
      center.add(request)


  }

我希望设置特定的日期和时间来触发本地通知。

【问题讨论】:

    标签: ios swift


    【解决方案1】:

    您必须使用UNCalendarNotificationTrigger 而不是UNTimeIntervalNotificationTrigger 并且UILocalNotificaion 已弃用

        let mutable = UNMutableNotificationContent()
        mutable.body = "message"
        mutable.title = "title"
    
        var date = DateComponents()
        date.hour = 16
        date.minute = 52
        date.month = 6
        date.day = 20
        date.year = 2019
    
        let trigger = UNCalendarNotificationTrigger(dateMatching: date, repeats: false)
        let request = UNNotificationRequest(identifier: "key", content: mutable, trigger: trigger)
        UNUserNotificationCenter.current().add(request)
    

    【讨论】:

      【解决方案2】:

      此代码将帮助您了解如何每天发送本地通知。您可以设置小时和分钟。

      func setUpLocalNotification(_ hour: Int, _ minute: Int) {
          print("Local Notification Setup")
      
          let calendar = NSCalendar(identifier: .gregorian)!;
      
          var dateFire = Date()
      
          // if today's date is passed, use tomorrow
          var fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire)
      
          if (fireComponents.hour! > hour
              || (fireComponents.hour == hour && fireComponents.minute! >= minute) ) {
      
              dateFire = dateFire.addingTimeInterval(86400)  // Use tomorrow's date
              fireComponents = calendar.components( [NSCalendar.Unit.day, NSCalendar.Unit.month, NSCalendar.Unit.year, NSCalendar.Unit.hour, NSCalendar.Unit.minute], from:dateFire);
          }
      
          /// -> If you want to get tomorrow date you can use this code.
          /*
          dateFire = dateFire.tomorrow!
       */
      
          // set up the time
          fireComponents.hour = hour
          fireComponents.minute = minute
      
          // schedule local notification
          dateFire = calendar.date(from: fireComponents)!
      
          let localNotification = UILocalNotification()
          localNotification.fireDate   = dateFire
          localNotification.alertBody  = "alert body"
          localNotification.alertTitle = "alert title"
          localNotification.repeatInterval = NSCalendar.Unit.day
          localNotification.soundName = UILocalNotificationDefaultSoundName;
      
          UIApplication.shared.scheduleLocalNotification(localNotification);
      }
      
      extension Date {
      
          var tomorrow: Date? {
              return Calendar.current.date(byAdding: .day, value: 1, to: self)
          }
      }
      

      【讨论】:

      • 我怎样才能得到明天的日期?
      • dateFire = dateFire.addingTimeInterval(86400) ,你可以使用这个代码。
      • 你能用明天的日期更新你的 ans 吗?我怎样才能获得86400 值?
      最近更新 更多