Swift- Get how much sec/millisecond passes since timer started - ios

trying to figure out how to get the time passed since timer started.
this is what i did :
Feel free to suggest other ways to get the time passed since the page loaded
Declared timer :
var runner = NSTimer()
runner = NSTimer.scheduledTimerWithTimeInterval(0.6, target: self, selector: Selector("time"), userInfo: nil, repeats: true)
Than tried this in the function,returns the interval i set(obviously)
func time() {
println(self.runner.timeInterval)
}
anyway if getting how much time passes since it started? (it's in the didload section so it like saying how much time passes since the page loaded). thanks ! :D

Put this in a playground. I added the loop just to create a time lag. Time in seconds down to fractions of a second.
var startTime = NSDate.timeIntervalSinceReferenceDate()
var currentTime: NSTimeInterval = 0
for var i = 0; i < 10000; i++ {
if i == 99 {
currentTime = NSDate.timeIntervalSinceReferenceDate()
println(i)
}
}
var elapsedTime = currentTime - startTime
println(Double(elapsedTime))
From:
https://developer.apple.com/library/ios/documentation/Cocoa/Reference/Foundation/Classes/NSDate_Class/#//apple_ref/occ/instp/NSDate/timeIntervalSinceReferenceDate
timeIntervalSinceReferenceDate
Returns the interval between the date object and January 1, 2001, at 12:00 a.m. GMT. (in seconds)
The method is establishing a startTime whenever you want to start. It is a time in seconds since the reference. Later we set the currentTime to be equal to the new time since the reference time. Subtracting one from the other gives elapsed time. There is several decimal place precision.

Related

How can I add minute to a custom DateComponent in Swift

I am trying to make an alarm app, where the app downloads alarm time from firebase. Now the will have to go consecutively 5 times with 1 minute time interval in between them. One possible way to tackle this problem is to make increment the time on the date component that's being passed in UNCalendarNotifications. Unfortunately DateComponent doesn't have a function to increment time, but date does.. and I can't figure out how to increment the time in given date component.
NB: I have tried converting date object to date and then increment time. But looks like Date only does it with current time.
You do not have to do anything with the date just check if the timestamp reached for the alarm to start then use a timer for repeat if 5 times.
Here is the code hope this help.
var timer:Timer?
var timeLeft = 60
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTimerFires), userInfo: nil, repeats: true)
#objc func onTimerFires()
{
timeLeft -= 1
if timeLeft <= 0 {
timer.invalidate()
timer = nil
//TODO: ring the alarm now
}
}

Adding elapsed TimeInterval to Date()

I'm trying to add the elapsed time to a Date() object (its for the resume button of a timed operation).
Below is the resume portion of the code responsible for calculating the altered startDate. I'm expecting it to add the elapsed TimeInterval to startDate.
This is the code:
print(startDate)
let elapsed = resumeTime - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)
This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.
Output:
2016-11-17 08:24:15 +0000
110.831687986851
2016-11-17 08:26:06 +0000
The second printed date should be more like:
2016-11-17 08:24:18 +0000
The definition for addTimeInterval is:
Add a TimeInterval to this Date.
Isn't this exactly what I want? Am I interpreting this incorrectly?
Note, resumeTime is defined when the pause button is tapped. It is set like this:
resumeTime = Date.timeIntervalSinceReferenceDate
Thanks.
This is the output when I paused the timer for about 3 seconds after about 2 minutes of runtime.
Although, your elapsed time is 2 min.
Make sure that you start elapsed in the right place, also make sure that this line generates the desired timestamp:
resumeTime = Date.timeIntervalSinceReferenceDate
Here is example of code very similar to yours, addTimeInterval does work well.
let resume = Date().timeIntervalSinceReferenceDate + 2
print(startDate)
let elapsed = resume - startDate.timeIntervalSinceReferenceDate
print(elapsed)
startDate.addTimeInterval(elapsed)
print(startDate)
Output
2016-11-17 08:53:34 +0000
2.00815904140472
2016-11-17 08:53:36 +0000
I think the mistake in your code is that you never set the startDate again, so your elapsed calculation is always based on when the app first ran, not the time elapsed since the last time you paused.

clock() doesn't work properly on iOS

I want to get the CPU time used by a function in my app. It works properly on iOS Simulator. but when I run it on my iPhone it just gives 0.
var t = clock()
myLongRunningFunction()
t = clock() - t
I'm not familiar with the clock() function. Is that a UNIX function?
Terminal has a man page for a clock function but it says that it reports the processor time used in the current process.
I would suggest using the NSDate timeIntervalSinceReferenceDate function instead. That gives a value in seconds and decimal fractions of a second:
var startTime: NSTimeInterval
startTime = NSDate.timeIntervalSinceReferenceDate()
myLongRunningFunction() let secondsToRun =
NSDate.timeIntervalSinceReferenceDate() - startTime
print(format: "function took %.5f seconds to run", secondsToRun)
Where your result will be expressed in floating-point seconds.

Swift: Trying to make a app that counts down the time from the present until one hour later [duplicate]

This question already has answers here:
How can I make a countdown timer like in a music player?
(2 answers)
Closed 7 years ago.
I'm trying to make an app that tell us the rest of time from the present time till one hour later.
This is the code but now it only has a function that tell us the countdown time by decreasing one second from the present time.
I'm thinking that I haven't definite the definition of the "cnt"
so that's why I'm thinking it doesn't work.
Can somebody tell me the reason and a solution?
import UIKit
class ViewController: UIViewController {
var cnt : Int = 0
var timer : NSTimer!//NSTimerというデフォルト機能から引っ張る
var myInt:Int = 0
override func viewDidLoad() {
let myDate: NSDate = NSDate()
let myCalendar: NSCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components([.Year, .Hour, .Minute, .Second],
fromDate: myDate) // myDate、すなわちNSDateから要素として引っ張り出してる
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "onUpdate:", userInfo: nil, repeats: true)//カウントダウンのインターバル
timer.fire()
var myStr: String = "\(myComponents.hour)"
myStr += "\(myComponents.minute)"
myStr += "\(myComponents.second)"
myInt = Int(myStr)! // toInt()がSwift2より無効になったようです。myInt=Str(my components,hour,minute,second)=現時刻
}
func onUpdate(timer : NSTimer){
cnt += 1//cnt+1=cnt,
let count = myInt - cnt //残り時間=現在時刻ー現在時刻に1時間足した時刻
print(count) // println()は、Swift2よりDeprecatedになりました。
}
}
It is difficult to understand what you're asking, but I will do my best.
In your viewDidLoad method, you're setting myInt to the integer representation of myStr. If the time is 18:30:50, myInt will be equal to 183050. That is not an appropriate representation of the time. Time is base 60, integers are base 10, for one thing. If you want to represent time as a single number, you can use timeIntervalSinceDate, or timeIntervalSinceReferenceDate or timeIntervalSince1970 to get the NSTimeInterval (ie. fractional seconds) representation of the date relative to a certain epoch either of your choosing or one built into Foundation.
Subtracting 1 from myInt each time the timer fires isn't going to give you an indication of the time remaining.
Also, NSTimer is not an accurate way to keep time. You should instead save the start date as a property and determine the time remaining based on timeIntervalSinceDate
e.g.
func onUpdate(timer : NSTimer){
let currentTime = NSDate()
let timeElapsed = currentTime.timeIntervalSinceDate(myDate)
println(timeElapsed)
}
If you want to show time elapsed in minutes, you can divide it by 60. You can look into NSDateComponentsFormatter to easily get a string representation of time intervals.
If you want the countdown to stop after an hour, then check for when timeElapsed is over 3600.
If you want it to show a countdown from 1 hour, then subtract the timeElapsed from 3600.

UILocalNotification multiple firing swift

So, I am trying to make a UILocalNotification that fires multiple times per instance. That is, user chooses his iteration interval (i.e. every 2 hours) and also chooses the date when the notification would stop (i.e. 01.11.2015.) using the DateTimePicker.
I've looked for several answers and in every answers there was always one solution missing and since I am relatively new to iOS Dev, I don't know how to correctly implement them.
Most of the issues was the iteration value and the end date triggering properly. Can anyone help?
You would need to use something like NSTimer to schedule a repeated task like so (the time is in seconds):
var interval = 60.0 // user chosen interval
var helloWorldTimer = NSTimer.scheduledTimerWithTimeInterval(interval, target: self, selector: Selector("helloWorld"), userInfo: nil, repeats: true)
func helloWorld()
{
println("Hello, World!")
}
Then you would also need to set up another timer similar to above which checks the date (in this example it does so every hour, but you can increase/decrease the accuracy by changing the interval). Once the dates match you then invalidate the previous timer to stop it repeating:
let chosenDate = "01.11.2015" // example date chosen with your DateTimePicker
var dateTimer = NSTimer.scheduledTimerWithTimeInterval(60.0 * 60, target: self, selector: Selector("checkDate"), userInfo: nil, repeats: true)
func checkDate() {
let date = NSDate()
println(date)
let formatter = NSDateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let formattedDate = formatter.stringFromDate(date)
if formattedDate == chosenDate {
helloWorldTimer.invalidate() // disable previous timer
dateTimer.invalidate() // must also stop this timer as attempting to invalidate the other once already stopped would cause a crash
}
}
n.b. make sure your dates are both in the same format for comparison
n.b.2. this is written using Swift 1.2
Use NSTimer' scheduledTimerWithTimeInterval:target: selector:userInfo:nil repeats: to trigger and stop notifications based on user's selected values.
Running NSTimer in Background

Resources