我的事件日期输出正确,我的页面没有错误,但我的应用程序崩溃了,请帮忙?
我相信这可能与将我的 NSString 日期转换为 NSDate 有关
NSLog("This is the EventDate: \(eventdate)")
let date = eventdate as? NSString
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
var DateInFormat = dateFormatter.stringFromDate((date as? NSDate)!)
var notification:UILocalNotification = UILocalNotification()
notification.alertBody = "\(eventtitle) is about to start at the \(rsPubName)"
notification.category = "FIRST_CATEGORY"
notification.alertAction = "heyaaa"
notification.fireDate = date as? NSDate!
NSLog("This is the date: \(date)")
UIApplication.sharedApplication().scheduleLocalNotification(notification)
最佳答案
有很多错误。
首先,您不能简单地将 NSString
转换为 NSDate
,反之亦然。您需要使用 NSDateFormatter()
提供的函数,例如 dateFromString()
或 stringFromDate()
。
其次,当您没有在代码中的任何地方使用 DateInFormat
时,为什么要这样做?
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-dd HH:mm:ss"
var DateInFormat = dateFormatter.stringFromDate((date as? NSDate)!)
第三,尝试使用类似这样的东西来设置日期:
let calendar = NSCalendar.currentCalendar()
let calendarComponents = NSDateComponents()
calendarComponents.hour = 8
calendarComponents.second = 0
calendarComponents.minute = 0
calendarComponents.day = 1
calendarComponents.year = 2015
calendarComponents.month = 2
let dateToFire = calendar.dateFromComponents(calendarComponents)
希望这对您有所帮助。 :)
关于swift - 如何为 UILocalNotifiication 设置 NSDate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35254675/