i have added a segmented control in my project to set a notification frequency (like daily, weekly, ecc..). I don't understand how to save the user choice and how to set notification on this choice. I have an AddController where user can insert reminders and in this controller i want also to set the frequency for notification repeat. The code is:
#IBAction func salva(sender: UIButton) {
if fieldNomeMedicina.text.isEmpty &&
fieldData.text.isEmpty &&
fieldDosaggio.text.isEmpty{
//alertView che avverte l'utente che tutti i campi sono obbligatori
//return
}
var therapy = PillsModel(nomeMedicinaIn: fieldNomeMedicina.text,
dosaggioIn : fieldDosaggio.text,
dataIn: fieldData.text
)
profilo.therapyArra.append(therapy)
DataManager.sharedInstance.salvaArray()
DataManager.sharedInstance.detail.pillsTable.reloadData()
dismissViewControllerAnimated(true, completion: nil)
let stringDate = fieldData.text//get the time string
//format date
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "dd-MM-yyyy hh:mm" //format style. Browse online to get a format that fits your needs.
var date = dateFormatter.dateFromString(stringDate)
//date is your NSdate.
var localNotification = UILocalNotification()
localNotification.category = "FIRST_CATEGORY"
localNotification.fireDate = date
localNotification.alertBody = "Take your medicine:" + " " + fieldNomeMedicina.text + " " + fieldDosaggio.text
localNotification.timeZone = NSTimeZone.defaultTimeZone()
localNotification.applicationIconBadgeNumber = UIApplication.sharedApplication().applicationIconBadgeNumber + 1
UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}
#IBAction func frequencyControl(sender: UISegmentedControl) {
if(segmentedControl.selectedSegmentIndex == 0)
{
notification.repeatInterval = 0;
}
else if(segmentedControl.selectedSegmentIndex == 1)
{
notification.repeatInterval = .CalendarUnitDay;
}
else if(segmentedControl.selectedSegmentIndex == 2)
{
notification.repeatInterval = .CalendarUnitWeekday;
}
else if(segmentedControl.selectedSegmentIndex == 3)
{
notification.repeatInterval = .CalendarUnitMonth;
}
else if(segmentedControl.selectedSegmentIndex == 4)
{
notification.repeatInterval = .CalendarUnitMinute;
}
}
func drawAShape(notification:NSNotification){
var view:UIView = UIView(frame:CGRectMake(10, 10, 100, 100))
view.backgroundColor = UIColor.redColor()
self.view.addSubview(view)
}
func showAMessage(notification:NSNotification){
var message:UIAlertController = UIAlertController(title: "A Notification Message", message: "Hello there", preferredStyle: UIAlertControllerStyle.Alert)
message.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(message, animated: true, completion: nil)
}
I have the error: use of unresolved identifier 'notification'in func frequencyControl.
Your problem is that you only create the localNotification after the user clicks the button (which is a good design choice). That means you can't store information in it before, but that isn't necessary - you can always ask the UISegmentedControl what its current value is.
You basically need to transfer this block of code:
if(segmentedControl.selectedSegmentIndex == 0)
{
notification.repeatInterval = 0;
}
...
inside the salva function. And while you're at it, convert the if statements to a switch - this is much cleaner. It would look like:
var localNotification = UILocalNotification()
switch segmentedControl.selectedSegmentIndex {
case 0:
localNotification.repeatInterval = 0;
case 1:
localNotification.repeatInterval = .CalendarUnitDay;
...
}
Related
I wrote my fist app, very simple, that creates a user defined number of badges at random times during a user defined window of time. It works fine but after some time (not sure how long, 2-4 hours), all of the user input information reverts to the defaults of the program. The issue is it is supposed to run each day but it is annoying to have to set it each morning. I am not sure if this is a coding issue or if the app 'reboots' when it is not doing anything in the background. Note that this occurs on my iPhone 8 but not on the simulator (or I am not patient enough for it to occur on the simulator).
I have put several print and label to try to identify when it occurs; I am sure I am putting them in the correct places. I apologize for including so much code - I tried to weed some of the mistakes out but I do not know where the problem is.
import UserNotifications
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var EarlyTimePicker: UITextField!
#IBOutlet weak var LateTimePicker: UITextField!
#IBOutlet weak var NumQuestions: UITextField!
#IBOutlet weak var myLabel_Questions: UILabel!// Attached to the label box
#IBOutlet weak var myLabel_StartEndTime: UILabel!
#IBOutlet weak var myLabel_TestResetTime: UILabel!
#IBOutlet weak var myLabel_CurrentEarlyTime: UILabel!
private var earlyTimePicker: UIDatePicker?
private var lateTimePicker: UIDatePicker?
override func viewDidLoad() {
super.viewDidLoad()
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .badge, .sound]) { (granted, error) in //ask for permission in order to show messages on the lock screen
if granted {
print("Yay!")
} else {
print("D'oh")
}
}
earlyTimePicker = UIDatePicker()
earlyTimePicker?.datePickerMode = .time //change to .time
earlyTimePicker?.addTarget(self, action: #selector(ViewController.earlyTimeChanged(earlyTimePicker:)),for: .valueChanged)
lateTimePicker = UIDatePicker()
lateTimePicker?.datePickerMode = .time //change to .time
lateTimePicker?.addTarget(self, action: #selector(ViewController.lateTimeChanged(lateTimePicker:)),for: .valueChanged)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ViewController.viewTapped(gestureRecognizer:)))
view.addGestureRecognizer(tapGesture)
EarlyTimePicker.inputView = earlyTimePicker
LateTimePicker.inputView = lateTimePicker
}
#objc func viewTapped(gestureRecognizer: UITapGestureRecognizer){
view.endEditing(true)
}
var earlyTime=480
var earlyTimehour=0
var earlyTimeminute=0
#objc func earlyTimeChanged(earlyTimePicker: UIDatePicker){
let earlyTimeFormatter = DateFormatter()
earlyTimeFormatter.dateFormat = "h:mm a"
earlyTimeFormatter.amSymbol = "AM"
earlyTimeFormatter.pmSymbol = "PM"
EarlyTimePicker.text = earlyTimeFormatter.string(from: earlyTimePicker.date)
view.endEditing(true)
let earlyTimedate = earlyTimePicker.date
let earlyTimecomponents = Calendar.current.dateComponents([.hour, .minute], from: earlyTimedate)
earlyTimehour = earlyTimecomponents.hour!
earlyTimeminute = earlyTimecomponents.minute!
earlyTime = earlyTimecomponents.hour! * 60 + earlyTimecomponents.minute!
print("earlyTimehour: \(earlyTimecomponents.hour!)")
print("earlyTimeminute: \(earlyTimecomponents)")
print("earlyTime: \(earlyTime)")
print("Current Time: \(Date())")
}
var lateTime=1200
var lateTimehour=0
var lateTimeminute=0
#objc func lateTimeChanged(lateTimePicker: UIDatePicker){
let lateTimeFormatter = DateFormatter()
lateTimeFormatter.dateFormat = "h:mm a"
lateTimeFormatter.amSymbol = "AM"
lateTimeFormatter.pmSymbol = "PM"
LateTimePicker.text = lateTimeFormatter.string(from: lateTimePicker.date)
view.endEditing(true)
let lateTimedate = lateTimePicker.date
let lateTimecomponents = Calendar.current.dateComponents([.hour, .minute], from: lateTimedate)
lateTimehour = lateTimecomponents.hour!
lateTimeminute = lateTimecomponents.minute!
lateTime = lateTimecomponents.hour! * 60 + lateTimecomponents.minute!
let testMinute = lateTime % 60
let testHour = lateTime / 60
print("lateTimehour: \(lateTimecomponents.hour!)")
print("lateTimeminute: \(lateTimecomponents)")
print("lateTime: \(lateTime)")
print("testHour: \(testHour)")
print("testMinute: \(testMinute)")
myLabel_TestResetTime.text = "Time Set \(Date())"
myLabel_CurrentEarlyTime.text = "Current Early Time: \(earlyTime) / OnOff: \(OnOff)"
}
let PickedString = ["One","Two","Three","Four", "Five","Six","Seven","Eight"]
// #IBAction func TestCallFunction(_ sender: UIButton) {
// scheduleLocal()
// }
//NEED TO REPEAT THIS FUNCTION AT EARLY TIME - 10
//need to stop repeating with a cancel button (while bool true, do it, while false, stop. Default is false)
var RunDaily: Timer?
var OnOff = false
var QuestionNum = 1
#IBAction func Launch(_ sender: UIButton) {
OnOff = true
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
guard let QuestionNumA = Int(NumQuestions.text!) else { //This is how to get the UserInterface VALUE as a number
print("not a number!: \(String(describing: NumQuestions.text))")
return
}
print("Number of Questions: \(QuestionNumA)")
// var QuestionNum = 1
if QuestionNumA > 10 {QuestionNum=10} else {QuestionNum=QuestionNumA}
print("QuestionNumA:\(QuestionNumA) vs QuestionNum: \(QuestionNum)")
printStuff()
showMessage()
}
#IBAction func Stop(_ sender: UIButton) {
OnOff = false
printStuff()
}
func printStuff() {
if OnOff == true {
print("Bool is On : \(OnOff)")
RunDaily = Timer.scheduledTimer(timeInterval: 86400, target: self, selector: #selector(showMessage), userInfo: nil, repeats: true)//86400
}
if OnOff == false {
print("Bool is Off : \(OnOff)")
RunDaily?.invalidate()
let center = UNUserNotificationCenter.current()
center.removeAllPendingNotificationRequests()
}
}
func SaveDefaultData(){ // THis is the structure to SAVE input data for when the app relaunches (causes error when run.
let defaults = UserDefaults.standard
defaults.set("Date()", forKey:"key1")
//defaults.set(earlyTimePicker, forKey:"earlyTimePickerSet") cannot set earlyTimePicker. causes crash
// defaults.set(lateTimePicker, forKey:"lateTimePickerSet")
defaults.set(earlyTime, forKey:"earlyTimeSet")
defaults.set(lateTime, forKey:"lateTimeSet")
defaults.set(QuestionNum, forKey:"QuestionNumSet")
}
func SetDefaultData(){// THis is the structure to Set input for when the app relaunches
let defaults = UserDefaults.standard
if let savedValue = defaults.string(forKey: "key1"){
print("Here you will get saved value \(savedValue)")
} else {
print("No value in Userdefault,Either you can save value here or perform other operation")
defaults.set("Here you can save value", forKey: "key1")
}
if let earlyTimeValue = defaults.string(forKey: "earlyTimeSet"){
print("Here you will get saved value \(earlyTimeValue)")
earlyTime = UserDefaults.standard.value(forKey: "earlyTimeSet") as? Int ?? 485
} else {
print("No value in Userdefault,Either you can save value here or perform other operation")
defaults.set("Here you can save value", forKey: "earlyTimeSet")
earlyTime = 500
}
if let lateTimeValue = defaults.string(forKey: "lateTimeSet"){
print("Here you will get saved value \(lateTimeValue)")
lateTime = UserDefaults.standard.value(forKey: "lateTimeSet") as? Int ?? 1265
} else {
print("No value in Userdefault,Either you can save value here or perform other operation")
defaults.set("Here you can save value", forKey: "lateTimeSet")
lateTime = 1230
}
if let QuestionNumValue = defaults.string(forKey: "QuestionNumSet"){
print("Here you will get saved value \(QuestionNumValue)")
QuestionNum = UserDefaults.standard.value(forKey: "QuestionNumSet") as? Int ?? 4
} else {
print("No value in Userdefault,Either you can save value here or perform other operation")
defaults.set("Here you can save value", forKey: "QuestionNumSet")
QuestionNum = 2
}
}
#objc func showMessage() {
let center = UNUserNotificationCenter.current()
if lateTime <= earlyTime {
lateTime = earlyTime+1
if earlyTimehour <= 12 {
LateTimePicker.text = "\(earlyTimehour):\(earlyTimeminute) AM"
}
if earlyTimehour > 12 {
let EarlyTimeAfternoon = earlyTimehour - 12
LateTimePicker.text = "\(EarlyTimeAfternoon):\(earlyTimeminute) PM"
}
}
// center.removeAllPendingNotificationRequests()
// THIS IS WHERE ALL THE USER INPUT GETS INTO THE PROGRAM //
// guard let QuestionNumA = Int(NumQuestions.text!) else { //This is how to get the UserInterface VALUE as a number
// print("not a number!: \(String(describing: NumQuestions.text))")
// return
// }
//print("Number of Questions: \(QuestionNumA)")
// THIS IS WHERE ALL THE USER INPUT GETS INTO THE PROGRAM //
var RandHourArray:[Int] = [0]
var RandMinArray:[Int] = [0]
var RandQuestionArray:[Int] = [0]
var Counter = 1
// var QuestionNum = 1
//if QuestionNumA > 2 {QuestionNum=10} else {QuestionNum=QuestionNumA}
// print("QuestionNumA:\(QuestionNumA) vs QuestionNum: \(QuestionNum)")
for _ in 0 ... QuestionNum-1{
// Pick random times for badges
//let RandHour = Int.random(in: earlyTimehour ... lateTimehour)
let RandTimeMinFromMidnight = Int.random(in: self.earlyTime ... self.lateTime)
let ConvertRandTimeHours = RandTimeMinFromMidnight / 60
let ConvertRandTimeMinutes = RandTimeMinFromMidnight % 60
RandHourArray.append(ConvertRandTimeHours)
//let RandMin = Int.random(in: earlyTimeminute ... lateTimeminute)
RandMinArray.append(ConvertRandTimeMinutes)
let RandQuestion = Int.random(in: 0 ... self.PickedString.count-1)
RandQuestionArray.append(RandQuestion)
//print("RandTimeMinFromMidnight: \(RandTimeMinFromMidnight)")
// print("RandHourArray: \(RandHourArray)")
// print("ConvertRandTimeHours: \(ConvertRandTimeHours)")
// print("RandMinArray: \(RandMinArray)")
// print("ConvertRandTimeMinutes: \(ConvertRandTimeMinutes)")
}
myLabel_Questions.text = "# of questions: \(QuestionNum)"//\(QuestionNumA)"
myLabel_StartEndTime.text = "Start Time \(earlyTime) / End Time \(lateTime)"
let content_A = UNMutableNotificationContent()
content_A.title = "Prompt"
content_A.body = self.PickedString[RandQuestionArray[Counter]] //
content_A.categoryIdentifier = "alarm"
content_A.userInfo = ["customData": "fizzbuzz"]
content_A.sound = UNNotificationSound.default
var dateComponents_A = DateComponents()
dateComponents_A.hour = RandHourArray[Counter]
dateComponents_A.minute = RandMinArray[Counter]
let trigger_A = UNCalendarNotificationTrigger(dateMatching: dateComponents_A, repeats: false)
let request_A = UNNotificationRequest(identifier: UUID().uuidString, content: content_A, trigger: trigger_A)
center.add(request_A)
print("Request A time: \(RandHourArray[Counter]) : \(RandMinArray[Counter])")
print("Question String picked A: \(self.PickedString[RandQuestionArray[Counter]])")
Counter=2
if Counter<=QuestionNum {
let content_B = UNMutableNotificationContent()
content_B.title = "Prompt"
content_B.body = self.PickedString[RandQuestionArray[Counter]]
content_B.categoryIdentifier = "alarm"
content_B.userInfo = ["customData": "fizzbuzz"]
content_B.sound = UNNotificationSound.default
var dateComponents_B = DateComponents()
dateComponents_B.hour = RandHourArray[Counter]
dateComponents_B.minute = RandMinArray[Counter]
let trigger_B = UNCalendarNotificationTrigger(dateMatching: dateComponents_B, repeats: false)
let request_B = UNNotificationRequest(identifier: UUID().uuidString, content: content_B, trigger: trigger_B)
center.add(request_B)
print("Request B time: \(RandHourArray[Counter]) : \(RandMinArray[Counter])")
print("Question String picked B: \(self.PickedString[RandQuestionArray[Counter]])")
}
}
}
You should store your data inside UserDefaults, Keychain and Core Data or other stuff. if you dont store your data every time you close the application all the data will deallocate from the memory because they were stored in the heap.
Unsaved data:
let myLabel: UILabel = UILabel()
myLabel.text = "Some text"
Should save like:
UserDefaults.standard.setValue(myLabel.text, forKey: "it.is.custom")
And load like:
myLabel.text = UserDefaults.standard.value(forKey: "it.is.custom") as? String
refrence to study: https://fluffy.es/persist-data/
func editFutureEventToCalendar(id:String,title: String, description: String?,alarams :[EKAlarm],location:String,contacts:[GenParticipants],repeatString :String,timeZone:NSTimeZone, startDate: NSDate, endDate: NSDate , isAllDay :Bool,calendar:EKCalendar,StruLocation:EKStructuredLocation?)->Bool {
let eventStore = EventsManager.getEventStore()
let event = EventsManager.geteventID(id: id)
let ocdate = event.occurrenceDate
event.title = title
event.startDate = startDate as Date
event.endDate = endDate as Date
event.notes = description
event.calendar = calendar
// event.occurrenceDate = ocdate
event.timeZone = timeZone as TimeZone //timezoneNSTimeZone() as TimeZone //timeZone as TimeZone
event.isAllDay = isAllDay
if StruLocation != nil {
event.structuredLocation = StruLocation
}else {
event.structuredLocation = StruLocation
}
if repeatString != "None" {
if event.hasRecurrenceRules {
let rrrl = event.recurrenceRules
for i in rrrl! {
event.removeRecurrenceRule(i)
}
}
let rule = EventsManager.getRepeatValue(repeatString)//self.getRepeatValue(option: repeat)
event.addRecurrenceRule(rule!)
}else if repeatString == "None"{
if event.hasRecurrenceRules {
let rrrl = event.recurrenceRules
for i in rrrl! {
event.removeRecurrenceRule(i)
}
}
}
for item in alarams {
event.addAlarm(item)
}
// event.location = location
// let formatter = CNContactFormatter()
// formatter.style =
var attendees = [EKParticipant]()
// for item in contacts {
//
// let con = event.(contact: item)
// attendees.append(con!)
//
// }
do {
try eventStore.save(event, span: .futureEvents, commit: true)
//try eventStore.save(event, span: .thisEvent)
return true
} catch let e as NSError {
EZAlertController.alert(e.debugDescription)
}
return false
}
I have this function for editing all the future events in repeat series - if i edit the event in between the series of events its deleting all the previous events and editing future events .
i want it to edit all the events in series .
I am using eventKit not eventKitUI . i dont want eventkitUI.
How to edit this function to do the same or do i have to fetch the event differently as the identifier are same for all the events in repeating series?
HI guys I have a date picker calculation app and Im wondering why the selected dates are not prtinting to my text lable. This is the code I have
#IBAction func calculateDays(sender: UIButton) {
if startDateTextField.text == "" || endDateTextField == "" {
let alert2 = UIAlertController(title: "Oops!", message: "Please Select a Start Date!", preferredStyle: UIAlertControllerStyle.Alert)
alert2.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert2, animated: true, completion: nil)
}
else {
let start = String(startDateTextField.text)
let end = String(endDateTextField.text)
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-yyyy"
guard let startDate = dateFormatter.dateFromString(start), endDate = dateFormatter.dateFromString(end) else {
// You don't have dates, show error(print("error"), do no nothing - your choice.
return
}
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day], fromDate: startDate, toDate: endDate, options: [])
let secondNewString = "\(components.day) days"
resultNumberOfDays.text = secondNewString
}
}
If I force unwrap as a test it works using (obviously this isn't safe)
let startDate:NSDate = dateFormatter.dateFromString(start)!
let endDate:NSDate = dateFormatter.dateFromString(end)!
any ideas on how to get the calculated dates to appear or letting me know what I'm missing here
thanks
In my collection view cell, I have a button which successfully saves the current user (PFUser) to an array of users of each event (which are the objects at index path).
However, I would like to add an alert view, but have been unsuccessful in putting the enormous chunk of code inside the alert action block. I suppose I could create another method but I feel there's a simpler way to do it.
When I tried putting it in, A. the sheer number of brackets threw me off a bit and B. it didn't recognize "alertController" anymore at the bottom of the method.
Thanks for the help like always.
func buttonTapped(sender: AnyObject) {
let button = sender as! UIButton
let view = button.superview
let cell = view?.superview as! EventCell
let indexPath = collectionView.indexPathForCell(cell)
// print(indexPath)
if let indexPath = indexPath {
if let event = events?[indexPath.row] {
//pops alert vc
var alertController : UIAlertController = UIAlertController(title: event.eventTitle, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveUserToEvent = UIAlertAction(title: "Yes", style: .Default) { _ in
// WHAT TO DO HERE? I want to add the stuff below
}
alertController.addAction(saveUserToEvent)
var attendees = [String]()
if let attendeesTmp = event["attendees"] as?[String] {
attendees = attendeesTmp;
}
if let objId = PFUser.currentUser()?.objectId {
var found = false
for objIdd in attendees {
if objIdd == objId {
found = true
break;
}
}
if !found {
attendees.append(objId)
event["attendees"] = attendees;
event.saveInBackground()
}
}
if let user = PFUser.currentUser() {
var eventsAttending = [String]()
if let eventsAttendingTmp = user["eventsToAttend"] as?[String] {
eventsAttending = eventsAttendingTmp;
}
if let eventId = event.objectId {
var found = false
for eventIdd in eventsAttending {
if eventIdd == eventId {
found = true
break;
}
}
if !found {
eventsAttending.append(eventId)
user["eventsToAttend"] = eventsAttending;
user.saveInBackground()
}
}
}
}
}
}
Did you put
alertController.addAction(saveUserToEvent)
In the brackets as well? It stays outside.
This should work
func buttonTapped(sender: AnyObject) {
let button = sender as! UIButton
let view = button.superview
let cell = view?.superview as! UITableViewCell
let indexPath = collectionView.indexPathForCell(cell)
// print(indexPath)
if let indexPath = indexPath {
if let event = events?[indexPath.row] {
//pops alert vc
var alertController : UIAlertController = UIAlertController(title: event.eventTitle, message: nil, preferredStyle: UIAlertControllerStyle.Alert)
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
alertController.addAction(cancelAction)
let saveUserToEvent = UIAlertAction(title: "Yes", style: .Default) { _ in
var attendees = [String]()
if let attendeesTmp = event["attendees"] as?[String] {
attendees = attendeesTmp;
}
if let objId = PFUser.currentUser()?.objectId {
var found = false
for objIdd in attendees {
if objIdd == objId {
found = true
break;
}
}
if !found {
attendees.append(objId)
event["attendees"] = attendees;
event.saveInBackground()
}
}
if let user = PFUser.currentUser() {
var eventsAttending = [String]()
if let eventsAttendingTmp = user["eventsToAttend"] as?[String] {
eventsAttending = eventsAttendingTmp;
}
if let eventId = event.objectId {
var found = false
for eventIdd in eventsAttending {
if eventIdd == eventId {
found = true
break;
}
}
if !found {
eventsAttending.append(eventId)
user["eventsToAttend"] = eventsAttending;
user.saveInBackground()
}
}
}
}
alertController.addAction(saveUserToEvent)
}
}
}
I want to disable previous time ie before current time from datePicker,As in date picker we can use minimum Date to do this.how could we do the same with time picker.
Here is the Code.`
timePicker = [[UIDatePicker alloc] init];
[self.view addSubview:timePicker];
float tempHeight = timePicker.frame.size.height;
timePicker.frame = CGRectMake(0,200 ,self.view.frame.size.width , tempHeight);
timePicker.hidden = YES;
timePickerFormatter= [[NSDateFormatter alloc]init ];
[timePickerFormatter setDateFormat:#"HH:mm"];
**timePicker.datePickerMode = UIDatePickerModeCountDownTimer;**
timePicker.minuteInterval=15;
`
Thanks in Advance Please suggest me if any way to perform this.
In the default UIDatePicker minimum date can be set and the date property has both date and time values and you can set it there itself
[datePicker setMinimumDate:[NSDate date]];
Here
[NSDate date]
gives current date
So you want to disable previous time from current time.
timePicker.date = [NSDate date];
this sets the time to current time, but i don't think you can disable the previous time.
By This method you can provide alert to user if he/she selected the past time time. Condition is that you already placed a check on minimum date as current day.
func handleTimePicker(sender: UIDatePicker) {
let timeFormatterHour = NSDateFormatter()
let timeFormatterMinutes = NSDateFormatter()
timeFormatterHour.dateFormat = "hh"
timeFormatterMinutes.dateFormat = "mm"
let InputTimeHourString = timeFormatterHour.stringFromDate(sender.date)
let InputTimeMinutesString = timeFormatterMinutes.stringFromDate(sender.date)
let InputTimeHourInt = Int(InputTimeHourString)!
let InputTimeMinutesInt = Int(InputTimeMinutesString)!
let calculatedInputMinutes = (InputTimeHourInt * 60) + InputTimeMinutesInt
let TodayTime = NSDate()
let TodayTimetimeFormatterHour = NSDateFormatter()
let TodayTimetimeFormatterMinutes = NSDateFormatter()
TodayTimetimeFormatterHour.dateFormat = "hh"
TodayTimetimeFormatterMinutes.dateFormat = "mm"
let TodayTimeInputTimeHourString = TodayTimetimeFormatterHour.stringFromDate(TodayTime)
let TodayTimeInputTimeMinutesString = TodayTimetimeFormatterMinutes.stringFromDate(TodayTime)
let TodayTimeInputTimeHourInt = Int(TodayTimeInputTimeHourString)!
let TodayTimeInputTimeMinutesInt = Int(TodayTimeInputTimeMinutesString)!
let TodayTimecalculatedInputMinutes = (TodayTimeInputTimeHourInt * 60) + TodayTimeInputTimeMinutesInt
if TodayTimecalculatedInputMinutes - calculatedInputMinutes < 0
{
let shownDateFormatter = NSDateFormatter()
shownDateFormatter.dateFormat = "hh:mm a"
self.txtTimeEvent.text = shownDateFormatter.stringFromDate(sender.date)
}
else
{
let alertController = UIAlertController(title: "Time Selection Problem", message:
"You cannot select the Past time", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default,handler: nil))
self.presentViewController(alertController, animated: true, completion: nil)
let shownTime = NSDate()
let shownTimeFormatter = NSDateFormatter()
shownTimeFormatter.dateFormat = "hh:mm a"
self.txtTimeEvent.text = shownTimeFormatter.stringFromDate(shownTime)
}
}
Swift : Add this line in your Picker Function.its Only allow future Time.
My_Pickername.minimumDate = NSDate()
You posted your question two years ago but this may help anyone who will face this issue, I had the same problem today, and here's the solution:
It doesn't really disable previous dates, but if a user selects a previous date, the above function will display an alert and reset the UIDatePicker to the current date :
Swift 4 :
#IBAction func dateChanged(_ sender: Any) {
let dtp = sender as! UIDatePicker
if Date() <= dtp.date {
print ("correct date")
} else {
dtp.date = Date()
let alert = UIAlertController(title: "Error", message: "You have to choose a correct date", preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
self.present(alert, animated: true, completion: nil)
}
}