在我的应用程序中,我为某些事件设置了本地通知。但是,NSDateFormatter
不能正确格式化日期和时间。当我格式化日期时,它会提前 3 小时。同样,当我使用 获取当前时间时NSDate()
,它会提前 3 小时作为 UTC。我的应用程序中的另一个事件也遇到了同样的问题,但我可以通过添加dateFormatter.timeZone = NSTimeZone(name: "GMT")
. 当前问题与以下代码有关:
var dateFormatter1 = NSDateFormatter()
var dateFormatter2 = NSDateFormatter()
dateFormatter1.dateFormat = "yyyy-MM-dd"
dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm"
let mainItemList: Array<BagItem> = self.GetMainItemsInfoInBag()
for(item) in mainItemList
{
let dateString = dateFormatter1.stringFromDate(item.date) + " " + item.time
// Send servey notification
let serveyNotificationTime = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: Int((120 + item.itemService.duration) / 60), toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)
self.SetUpLocalNotification(serveyNotificationTime, message: "Do you want to join to the servey?": true)
// if time for now is earlier than reservation time - 1 based on hour, set reminder notification.
if(NSDate().dateByAddingTimeInterval(3*60*60).compare(NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: -1, toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)!) == NSComparisonResult.OrderedAscending)
{
let reminderNotificationTime = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.CalendarUnitHour, value: -1, toDate: dateFormatter2.dateFromString(dateString)!, options: NSCalendarOptions.WrapComponents)
self.SetUpLocalNotification(reminderNotificationTime, message: message, withCategory: false)
}
}
// Set Up Local Notifications
private func SetUpLocalNotification(notificationTime: NSDate!, message: String!, withCategory: Bool!)
{
var app: UIApplication = UIApplication.sharedApplication()
var notifyAlarm: UILocalNotification! = UILocalNotification()
if(notifyAlarm != nil)
{
notifyAlarm.fireDate = notificationTime
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
if(withCategory == true)
{
notifyAlarm.category = "FIRST_CATEGORY"
}
notifyAlarm.soundName = UILocalNotificationDefaultSoundName
notifyAlarm.alertBody = message
app.scheduleLocalNotification(notifyAlarm)
}
}
在上面的代码中,我试图将本地通知设置为“提醒”和“加入服务”。但是,我无法正确设置本地通知时间。
谢谢您的回答
此致