无论如何,在 Swift 中用户每天选择的时间触发 UILocalNotification 吗?

Is there anyway to fire a UILocalNotification at a time user choose everyday in Swift?

我正在构建一个应用程序,需要每天在用户通过 UIDatePicker 设置的时间显示通知。

我的代码来自here:

@IBOutlet var myDatePicker: UIDatePicker!
@IBOutlet var mySwitch: UISwitch!

var localNotification = UILocalNotification()   // You just need one
var notificationsCounter = 0

// put your functions now
func datePicker()            { myDatePicker.datePickerMode = UIDatePickerMode.Time }
func notificationsOptions()  {
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = .CalendarUnitDay
    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
    localNotification.alertAction = "Open App"
    localNotification.alertBody = "Here is the seven o'clock notification"
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
    //     you may add arbitrary key-value pairs to this dictionary.
    //     However, the keys and values must be valid property-list types
    //     if any are not, an exception is raised.
    // localNotification.userInfo = [NSObject : AnyObject]?
}
func toggleSwitch(){
    if mySwitch.on{
        localNotification.fireDate = myDatePicker.date
    } else {
        localNotification.fireDate = NSDate(timeIntervalSinceNow: 999999999999)   // will never be fired
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    datePicker()
    notificationsOptions()
    // Do any additional setup after loading the view, typically from a nib.
}

// here is where you place your IBActions

@IBAction func switchPressed(sender: AnyObject) {
    toggleSwitch()
}

但是不行。

您可以将日期和时间从 date picker 传递到以下代码,

NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
//Pass here your values
[comps setDay:1]; 
[comps setMonth:1];
[comps setYear:2013];
[comps setHour:10];
[comps setMinute:10];
[comps setSecond:10];
localNotification.fireDate = [[NSCalendar currentCalendar] dateFromComponents:comps];

希望这段代码对您有所帮助。

自行解决。我不小心把 dateFormatter.dateFormat = "HH:mm:ss" 设置错了。