没有从LocalNotification.fireDate收到通知

时间:2014-12-10 17:29:56

标签: swift localnotification

为什么在按下按钮后没有显示通知?

如果fireDate为NSDate(timeIntervalSinceNow: 10),则可以正常使用

如何从阵列中获取通知?

    @IBAction func buttonPressed(sender: AnyObject) {

    var stringDate = dateFormatter.stringFromDate(timePicker.date)
    alarmArray.append(stringDate)

    let fixedAlarmArray = alarmArray
    NSUserDefaults.standardUserDefaults().setObject(fixedAlarmArray, forKey: "alarmArray")
    NSUserDefaults.standardUserDefaults().synchronize()


    //Local Notification
    var localNotification:UILocalNotification = UILocalNotification()
    localNotification.alertAction = "Go to app"
    localNotification.alertBody = "Its Time!"
    localNotification.fireDate = timePicker.date
    localNotification.timeZone = NSTimeZone.defaultTimeZone()
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)

    self.view.endEditing(true)

}

1 个答案:

答案 0 :(得分:0)

  

根据值解释fireDate中指定的日期   这个属性。如果指定nil(默认值),则触发日期为   解释为绝对GMT时间,适用于此类情况   作为倒数计时器。如果为此分配有效的NSTimeZone对象   属性,起火日期被解释为挂钟时间   当时区发生变化时自动调整;一个   适合这种情况的例子是一个闹钟。

localNotification.fireDate = timePicker.date
localNotification.timeZone = NSTimeZone.defaultTimeZone()
// the problem is here, you are setting the timezone after inputing your date

你应该使用localtimeZone并在设置fireDate

之前设置它
localNotification.timeZone = NSTimeZone.localTimeZone()
localNotification.fireDate = timePicker.date

注意:

  

在iOS 8及更高版本中,使用本地或远程通知的应用程序   必须注册他们打算提供的通知类型。该   系统然后给用户限制类型的能力   您的应用显示的通知。系统没有徽章图标,   显示警报消息,或播放警报声(如果有的话)   您的应用未启用通知类型,即使它们是   在通知有效负载中指定。

这样做:

UIApplication.sharedApplication().registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Badge | UIUserNotificationType.Sound | UIUserNotificationType.Alert, categories: nil))

创建一个扩展,将选择的时间与0秒相结合,如下所示:

extension NSDate {

    var day:            Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitDay,           fromDate: self).day           }
    var month:          Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMonth,         fromDate: self).month         }
    var year:           Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitYear,          fromDate: self).year          }
    var minute:         Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitMinute,        fromDate: self).minute }
    var hour:           Int { return NSCalendar.currentCalendar().components(NSCalendarUnit.CalendarUnitHour,          fromDate: self).hour   }

    var fireDate: NSDate {
        return NSCalendar.currentCalendar().dateWithEra(1, year: year, month: month, day: day, hour: hour, minute: minute, second: 0, nanosecond: 0)!
    }
}

然后使用它如下:

localNotification.fireDate = timePicker.date.fireDate