Strange date picker behaviour Xcode, swift 3 - swift

My current project is a timer which uses a date picker to set the amount of time the user wants before the timer goes off (say 1 minute, 6 hours and two minutes etc.). The problem lies in the amount of time that the date picker believes it has been set for. Below is the code which I am using to set the time.
#IBOutlet weak var datePicker: UIDatePicker!
var timeAmount:Double = 0
#IBAction func startButton() {
timeAmount = Double(datePicker.countDownDuration)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: timeAmount, repeats: false)
}
Here it can be seen that the function startButton, sets the value of timeAmount to be the amount of time that the date picker is set for. This timeAmount value is then used in a local notification as the time.
The issue is that the datePicker.countDownDuration is never correct. If it is set for one minute, then timeAmount may return a value of 99 seconds, 62 seconds, 67 seconds etc. It is just completely random.
Maybe I do not entirely understand how the .countDownDuration feature works, however from everything I have read, this should return a value of 60 seconds.
Any thoughts and suggestions on the matter will be very much appreciated, thank you.

By default, the UIDatePicker will take the current second value for the calculation.
timeAmount = (number of minutes selected in picker * 60) + current time second value.
For example:
If the current time is 13:40:25 (1 PM 40 minutes 25 seconds) and you have selected one minute in the date picker, the value of timeAmount in this case is 85.
timeAmount = (1*60) + 25
This will solve your problem.
Go to your Storyboard and select UIDatapicker. Navigate to Date option in Attributes inspector.
Click the Dropdown and change it to Custom from Current Date.
You will see a new text field with the current time as the custom date.
Just change the second field to 00.
Run the App now. Now it will take 0 as the value for the second and you will able to see seconds value correctly based on the time you are choosing in the date picker.
Hope this will solve your problem.

Related

UIDatePicker count Down timer mode doesn't return the correct time in Xcode 10.3

I'm working on a project in which the user can select a time interval (HH:mm) from a UIDatePicker in count down mode and, with that time interval, I want to trigger a notification.
I created the UIDatePicker in the Storyboard and set the Mode to Count Down Timer in the Attributes Inspector.
The problem is that when I get the current value of the datePicker, the value is never correct.
For example, if the user selects 1 minute, I get random values between 70 an 110 but never 60!
How is this possibile?
(The problem occurs with every selection)
This is how I get the current value:
timePicker.countDownDuration
and for testing purpose, I print it with
timePicker.countDownDuration.description
Maybe there is a bug or something that I don't know? (of course there is)
I tried to convert the value represented on the UIDatePicker in string a then, reconvert it in TimeInterval but if there is a better method it would be great.
Ok problem solved, maybe it's a bug of XCode.
The problem occurs when you build the datepicker from storyboard and set it's mode paramether to Count Down Timer.
To solve this problem, simply don't set the mode of the datepicker on count down timer from the storyboard but you need to set the mode programmatically with
timepicker.datePickerMode = .countDownTimer
Doing this, the problem is solved

Schedule function execution in swift

I'm developing a simple app in Swift and I need to schedule a function execution every 24 hours. I'm aware of the method:
DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: {
self.functionToCall()
})
that could solve my problem but, is this the right solution for a 24 hours delay?
Thanks
Theoretically, this is possible.
The problem is that your app would have to run in the foreground for 24 hours, which is very unlikely to happen. Unfortunately, you can not run background tasks just like that.
The solution:
Just make it look like the function would execute in the background. Every time the update function is called, simply save the Int(Date().timeIntervalSince1970) to UserDefaults. This works like a timestamp and saves the last time you called your update function. Every time in the viewDidLoad()-function (not sure if it's called the same on Mac apps, but you can imagine what I mean) call:
If let timestamp = UserDefaults.standard.integer(forKey: "yourTimestampKey") {
let currentTimestamp = Date().timeIntervalSince1970
if (currentTimestamp - timestamp) > 86400 { // number of seconds in 24 hours
// the last time your function was updated was at least 24h ago
update()
}
}
That's how you can make it appear like it was updated in the background. I use this all the time in my apps and it works perfectly.
EDIT:
Maybe, just in case the app does indeed run 24 hours in a row, I would set up the upper function that you posted first as well.

Possible Bug? Minimum Date UIDatePicker Swift

I set the minimum date in the date picker like so:
override func viewDidLoad() {
super.viewDidLoad()
datePicker.minimumDate = NSDate()
}
This does prevent the user from rolling back the date, sort of. The user can roll the date dial back but it just snaps back to the current date. The problem is that when this happens, the datetime is set to midnight instead of the current time for any and all future changes and it also executes the event that runs when the date changes. This is a problem when it comes to my code and sliders in my UI. It thinks that the date changed when it did not, yeah it bounces back but it's too late by this point my code runs assuming the date changed. How do I prevent the user from rolling the dial back at all?
Steps to reproduce:
1) Set minimum date as shown above.
2) Set up an event for date change
3) Set event to print(datePicker.date)
4) Roll Dial forward
5) Roll dial backward beyond current date.
6) Roll dial forward
Notice the time is now permanently set to midnight from this point forward.
A quick fix/workaround was to set datePicker.date = NSDate() in the date changed event function.

How to show Notification in Swift more than once?

Is there anyway to show the notification with swift every 15 seconds ? I checked that via
notification.fireDate=NSDate(timeIntervalSinceNow: 15)
but it doesn't work everytime it just showed once , how we can do it as a loop ?
You can't schedule a notification every 15 second. The minimum time between notifications it is 1 minute which it is also very unlikely needed.
var repeatInterval: NSCalendarUnit { get set }
Description The calendar interval at which to reschedule the
notification. If you assign a calendar unit such as weekly
(NSWeekCalendarUnit) or yearly (NSYearCalendarUnit), the system
reschedules the notification for delivery at the specified interval.
Note that intervals of less than one minute are not supported. The
default value is 0, which means that the system fires the notification
once and then discards it.
So just set it up as follow:
notification.repeatInterval = .Minute
You can set localNotification.repeatInterval property which as to be of type NSCalendarUnit

UIDatePicker, time, and 1970

I've come across a small issue that I've been chewing on for a day or two now.
Using the Apple example project called DateCell I lifted its UIDatePicker and set it to time. I used this particular code as it did the animated slide on/off the screen.
My workflow is to set four values, start time, lunch time out, lunch time in, and stop time. I set these values by using [NSDate date].
I then use NSCalander:component calls to do some math such as "add 30 minutes to start time to get lunch time out," and "start time - lunch time out - 8 hours to get stop time."
The initial setup goes just fine. Clicking on the start time cell brings up the picker, and selecting a time change the other three times following my simple math formula's.
If the second row is selected, the lunch time out, the wheel comes up again to pick your lunch time out time. However this is where my problems start. It seems that my UIDatePickerModeTime wheel returns a date portion for January 1, 1970. And its this date portion that messes up my math formulas.
My question is, what can I do to fix this?
I've tried setting an initial, minimum time, in the XIB for the picker. This sort of works but when you pick a time on the wheel, the wheel spins itself to the time set in the XIB. This method doesn't have a clean feel to it.
I've tried settings the initWithTimeInterval class methods, but these block out times and isn't what I'm looking for I think.
I've also tried the NSDateFormatter:stringFromDate|dateFromString calls, and these had no affect.
What I have not done yet:
Custom defined date/time string.
Rebuilding UIDatePicker:Time from scratch
Am I over looking anything?
Thanks.
I've solved my problem, and here is how I addressed it.
Before I get to my answer I'm still really new to Objective-C and object oriented programming so my vocabulary doesn't know how to describe some of the things I've tried explaining. So take this into account when reading this.
Using UIDatePicker in time mode, i.e. you go into your NIB/XIB file and set your UIDatePicker object to 'time', will only return time. This is where I went wrong.
Using the NSDateComponent or any of the NSCalendar methods will bring out the date component of the picker. Thus you'll see January 1st, 1970 in the NSLog returns for example.
I had to find a new way of doing my math and manipulation of the times I was getting from the picker.
What I ended up using is NSTimeInterval, dateByAddingTimeInterval, and timeIntervalSinceDate. Research showed that NSTimeInterval is also a float type, so I used float to do some math as well.
Here an example -
if (indexPath.row == [labelArray indexOfObjectIdenticalTo:#"Clock Out"])
{
NSTimeInterval diffClockInOutToLunch = [outToLunch timeIntervalSinceDate:clockIn];
float remainingInTheDay = 28800 - diffClockInOutToLunch;
self.clockOut = [inFromLunch dateByAddingTimeInterval:remainingInTheDay];
cell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockOut];
self.clockOutIndex = indexPath;
return cell;
}
I'm using a TableView to display my fields. When this 'if' statement is tripped it will populate the detailTextLabel of the line displaying "Clock Out." Visually the phrase "Clock Out" will be on the left side of the row, the time will be on the right side.
diffClockInOutToLunch is defined as a NSTimeInterval type. The operation being performed is timeIntervalSinceDate which essentially subtracts the value of outToLunch from the value of clockIn. Imagine outToLunch as being 11:00pm and clockIn as being 6:00am. This difference is 5 hours. NSTimeInterval stores values as seconds only so this difference of 5 hours is 18000 seconds.
I then perform a normal math operation using float. In this case I want to find out how many hours remain in the work day. This assumes the hours worked in a day is 8 hours. Because NSTimeInterval returns seconds, I converted 8 hours into seconds (28,800 seconds) and then subtract diffClockInOutToLunch from 28800. Now remainingInTheDay is equal to to 10800, or 3 hours.
The next operation I perform is set clockOut to the time our work day is finished. To do this I use the dateByAddingTimeInterval operation, which also is a NSDate method, so whatever it returns will be in a date/time format. In this operation we add remainingInTheDay (10,800 seconds) to inFromLunch (11:30am for example). Our clockOut time is now 2:30pm which is then sent through my DateFormatter and returned as a string to the cell of the TableView and also stored for later use.
Here's another example, from further down in my code -
- (void)clockInChanged
{
// Set clockIn value
self.clockIn = self.pickerView.date;
// Change the outToLunch time
self.outToLunch = [self.pickerView.date dateByAddingTimeInterval:5*60*60];
UITableViewCell *outToLunchCell = [self.tableView cellForRowAtIndexPath:outToLunchIndex];
outToLunchCell.detailTextLabel.text = [self.dateFormatter stringFromDate:outToLunch];
// Change the inFromLunch time
self.inFromLunch = [outToLunch dateByAddingTimeInterval:30*60];
UITableViewCell *inFromLunchCell = [self.tableView cellForRowAtIndexPath:inFromLunchIndex];
inFromLunchCell.detailTextLabel.text = [self.dateFormatter stringFromDate:inFromLunch];
// Change the clockOut time
NSTimeInterval diffClockInOutToLunch = [outToLunch timeIntervalSinceDate:clockIn];
float remainingInTheDay = 28800 - diffClockInOutToLunch;
self.clockOut = [inFromLunch dateByAddingTimeInterval:remainingInTheDay];
UITableViewCell *clockOutCell = [self.tableView cellForRowAtIndexPath:clockOutIndex];
clockOutCell.detailTextLabel.text = [self.dateFormatter stringFromDate:clockOut];
}
In this example, we've previously determined that the row pertaining to "Clock In" time was selected ("Touch Up Inside" if you will) and we drop to this method.
What happens in this method is whenever clockIn is changed using the picker, the times displayed in outToLunch, inFromLunch, and clockOut automatically update and are displayed.
This example shows that we capture the value on the picker (self.pickerView.date) as clockIn. We then use clockIn to seed our mess of dateByAddingTimeInterval's and so forth.
So. This is how I managed my times using UIDatePicker (which is set to time mode).
The short answer would be I was using the wrong methods to work with what my picker was turning.
I hope this helps you and hopefully it'll be here if I need it again too ;)