0
需要在設定的時間每天發送提醒。使用UIStepper將時間設置爲1到24小時的格式。修改後的代碼,但它仍然無法正常工作,不來通告使用UIStepper進行UILocalNotification的時間
var hour = 0.0
let notification = UILocalNotification()
@IBOutlet weak var remindStepper: UIStepper!
@IBOutlet weak var remindLabel: UILabel!
@IBOutlet weak var remindSwitch: UISwitch!
在viewDidLoad中()
remindStepper.wraps = true
remindStepper.value = hour
remindStepper.minimumValue = 0
remindStepper.maximumValue = 24
if NSUserDefaults.standardUserDefaults().objectForKey("hour") != nil { hour = NSUserDefaults.standardUserDefaults().objectForKey("hour") as! Double }
if NSUserDefaults.standardUserDefaults().objectForKey("remindOnOff") != nil { remindOnOff = NSUserDefaults.standardUserDefaults().objectForKey("remindOnOff") as! Bool
}
if remindOnOff == true {
remindSwitch.on = true
} else {
remindSwitch.on = false
}
remindLabel.text = "\(Int(hour)):00"
然後創建
func setEveryDayNotification(){
let calendar = NSCalendar.currentCalendar()
var dateFire = NSDate()
let components = calendar.components(.Hour,fromDate: dateFire)
components.calendar = calendar
components.hour = Int(hour)
dateFire = calendar.dateFromComponents(components)!
notification.alertTitle = "alert title"
notification.alertBody = "alert body"
notification.soundName = UILocalNotificationDefaultSoundName
notification.alertAction = "Run the workout"
notification.timeZone = NSTimeZone.defaultTimeZone()
notification.fireDate = components.date
notification.repeatInterval = NSCalendarUnit.Day
UIApplication.sharedApplication().scheduleLocalNotification(notification)
}
@IBAction func remindStepper(sender: UIStepper) {
NSUserDefaults.standardUserDefaults().setObject(Int(sender.value), forKey: "hour")
NSUserDefaults.standardUserDefaults().synchronize()
remindLabel.text = "\(Int(sender.value).description):00"
UIApplication.sharedApplication().cancelLocalNotification(notification)
remindOnOff = false
remindSwitch.on = false
NSUserDefaults.standardUserDefaults().setBool(remindOnOff, forKey: "remindOnOff")
}
@IBAction func remindSwitch(sender: UISwitch) {
if remindSwitch.on {
setEveryDayNotification()
remindOnOff = true
NSUserDefaults.standardUserDefaults().setBool(remindOnOff, forKey: "remindOnOff")
} else {
remindOnOff = false
UIApplication.sharedApplication().cancelLocalNotification(notification)
NSUserDefaults.standardUserDefaults().setBool(remindOnOff, forKey: "remindOnOff")
}
}
你能幫我實現我的任務嗎?謝謝 –
@ArturSkachkov你是否試過我寫過的代碼,那應該對你有幫助? – HardikDG
通知將觸發一次。進一步改變價值小時,什麼也沒有發生:( –