2016-02-07 27 views
2

我的事件日期输出正确,我的页面没有错误,但是我的应用崩溃了,请帮忙?如何为UILocalNotifiication设置NSDate

我认为它可能有一些与我的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) 
+0

有很多奇怪的可选事情正在进行。例如,'(date as?NSDate)!'非常有趣。为什么不使用'date as! NSDate'?此外,字符串不能简单地铸造日期。他们必须通过'NSDateFormatter'的'dateFromString:'方法。 – tktsubota

回答

0

有很多错误。

首先,您不能简单地将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) 

希望这有助于。 :)