【问题标题】:Set Local Notification for Specific Time设置特定时间的本地通知
【发布时间】:2016-11-06 16:13:35
【问题描述】:

我正在尝试安排本地通知,以便它在晚上 9:00 发生并每周重复一次。我有以下代码,并且一直收到一条错误消息,提示“无法将 NSDateComponents 类型的值分配给 .fireDate。我知道 .fireDate 只会接受 NSDate 类型,但是。我想不出一种方法来设置小时变量和分钟变量对于 NSDate 类型,因为我认为不可能这样做。

func Notification(){

    let dateComponents = NSDateComponents()
    dateComponents.day = 4
    dateComponents.month = 7
    dateComponents.year = 2016
    dateComponents.hour = 21
    dateComponents.minute = 00

    let Notification = UILocalNotification()

    Notification.alertAction = "Go Back To App"
    Notification.alertBody = "Did you complete your HH and QC?"
    Notification.repeatInterval = NSCalendarUnit.WeekOfYear
    Notification.timeZone = NSTimeZone.defaultTimeZone()

    Notification.fireDate = dateComponents
    UIApplication.sharedApplication().scheduleLocalNotification(Notification)
}

【问题讨论】:

  • 谷歌日历方法 dateFromComponents

标签: ios xcode swift nsdatecomponents localnotification


【解决方案1】:

这是你的做法。

在 Swift 2.0 上全面测试

//注意我已经从日期选择器中获取了日期时间

   func scheduleLocalNotification() {
        let localNotification = UILocalNotification()

        localNotification.fireDate = fixNotificationDate(datePicker.date)
        localNotification.alertBody = "Hey, you must go shopping, remember?"
        localNotification.alertAction = "View List" // Change depending on your action

        localNotification.category = "reminderCategory"

        UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    }

//此功能将帮助您生成火灾日期。

func fixNotificationDate(dateToFix: NSDate) -> NSDate {
    let dateComponets: NSDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Day, NSCalendarUnit.Month, NSCalendarUnit.Year, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: dateToFix)

    dateComponets.second = 0

    let fixedDate: NSDate! = NSCalendar.currentCalendar().dateFromComponents(dateComponets)

    return fixedDate
}

不要忘记请求推送通知的权限。

链接到我从事的项目 https://drive.google.com/open?id=0B2csGr9uKp1DR0ViZFZMMEZSdms

【讨论】:

    【解决方案2】:

    你应该像这样从日期组件中获取日期:

    let calendar = NSCalendar(identifier: NSCalendarIdentifierGregorian)!
    calendar.timeZone = NSTimeZone.localTimeZone()
    calendar.locale = NSLocale.currentLocale()
    let date = calendar.dateFromComponents(dateComponents)!
    Notification.fireDate = date
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-10
      • 2012-12-23
      • 1970-01-01
      • 2018-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多