Use NSTimer for better validation of beacon - ios

I have a program in SWIFT, that detects when a beacon or multiple beacons are out of range and based on
that it will perform something like saving some data into database and etc. Everything works well, however I do get lots of
false positive in a way that "didExitRegion" getting fired and few secs later "didEnterRegion" getting fired while I haven't been moved or etc.
I know this has lot to do with the tuning of the beacons and their qualities, but at this time I have come up with an alternative solution.
So I decided to use NSTimer to see if I am really off range or is it just a false positive that I am getting?
so when didExitRegion is getting fired, I start a NSTimer for 60 secs. If the 60 secs is up and didEnterRegion didn't get fire, then I know
I am really out of range and perform whatever data saving I need to do.
Otherwise if didEnterRegion is called within that 60 secs, then I'll assume it was a false positive and invalidate the
nstimer and not doing anything.
Everything works well as long as I am working with one beacon. The problem I have with timer is when multiple beacons go out of range.
lets say first beacon is out of range, so didExitRegion is getting fire and start the NSTimer
Let say 20 secs later second beacon is off range and again didExitRegion is getting fired and that one starts the NSTimer again.
Now my NStimer is all out of synch and at that time, things are not working correct and the NSTimer continuously start itself when 60 secs
is up and etc.
So my question is what is the work around this solution? How can I keep my nstimer in synch when is called again before is invalidated?
Is there a better way to this solution? Again, I know a better quality beacons can help, but that is not an option for me at this time.

One solution is to keep a dictionary like this:
var pendingExits = Dictionary<CLBeaconRegion,NSDate>()
Each time you get a didExitRegion call:
Only start the NSTimer if the dictionary is empty -- otherwise, assume the timer is already running.
Add the region to the dictionary along with a new NSDate() to set the timestamp of when it was added.
When you get a didEnterRegion callback:
Look for the region in the dictionary. If it is there, remove it.
When the timer goes off:
Look for any entry with a timestamp 60 seconds or more old. For this, remove the region from the dictionary and fire your custom exit logic.
Find the newest remaining timestamp (if any) in the dictionary. Start the timer to go off at that time plus 60 seconds.

Related

CMAltitudeData has some weird data at the end, any ideas?

I've been playing with Core Motion's framework lately and while trying to get more juice to come out of the limited CMAltitude class just stumbled with some weird data at the end of the call. So to recreate if you call up:
import UIKit
import CoreMotion
class ViewController: UIViewController {
let corey = CMAltimeter()
override func viewDidLoad() {
super.viewDidLoad()
self.getter()
}
#objc func getter() {
corey.startRelativeAltitudeUpdates(to: OperationQueue.main, withHandler: { (altitudeData:CMAltitudeData?, error:Error?) in
print(String(describing: altitudeData.unsafelyUnwrapped))
Just for the visual purposes doing this really scratchy thing will respond with:
Altitude -0.589237 Pressure 101093.882812 # 2377.566172
Altitude -0.618303 Pressure 101094.234375 # 2378.602637
Altitude -0.618303 Pressure 101094.234375 # 2379.640150
Altitude -0.620945 Pressure 101094.250000 # 2380.678124
Altitude -0.628872 Pressure 101094.343750 # 2381.714421
What I would like to know is the last part # 2381.714421, it looks like seconds but actually I'm not really sure, when comparing with a timer, and with boottime time_t that number start +4 seconds, after some time of inactivity it drifts and becomes less time than boottime.
Does it drifts away because of app inactivity?
But how come that it starts with more time than even boot-time?
Can anyone explain what's going on?
CMAltitudeData inherits from CMLogItem, this is where the last field, timestamp is coming from. According to the documentation, timestamp should match the amount of time in seconds since the device booted.
However, according to this question on SO the boot time can indeed drift slightly and it seems that timestamp doesn't simply copy time_t at each measurement, but rather it copies it at the first measurement and after that it just increments it based probably on a different Timer. Comparing to a Timer is not a good idea, since Timer runs on a runloop, so it only works while your app is in the foreground and even then it isn't really precise.

objective-c - NSTimer falling more and more behind

I have a NSTimer (running on main thread) that is supposed to go off every 0.02s. However, I notice that as memory usage start going up (the app captures a frame every tick and stores in an array) subsequent ticks begin to take more then 0.02s.
How can I solve this issue? I'm starting to think NSTimer is not suited for high-frequency tasks like this.
As the docs state,
A timer is not a real-time mechanism; it fires only when one of the
run loop modes to which the timer has been added is running and able
to check if the timer’s firing time has passed. Because of the various
input sources a typical run loop manages, the effective resolution of
the time interval for a timer is limited to on the order of 50-100
milliseconds.
Since 100 milliseconds = .1 seconds and your timer is supposed to run every 0.02 seconds, your timer schedule is far shorter than the timer's effective resolution and so you timer can easily get out of sync.

Show get updates every second on a NSTimer whose interval isn't 1

I'm trying to create a label that shows the time on a NSTimer, however my problem is that the interval on the timer isn't 1.0 and so there is no way to update the label every second like I would like to be able to. I have tried to synchronize two timers, however that is proving to be a challenge. So, Is there a way to get secondary updates or synchronize two timers of different interval?
I'm reading your question as follows:
I have a timer that needs to fire once per 5 seconds, but I would like to tell the user how many seconds remain until the timer fires.
The simplest way that I can think of is to make an intermediary method that the first timer will call. You would change:
timer -> METHOD_A
to
timer -> METHOD_B -> METHOD_A
the timer could then be set to update every .1 seconds, and METHOD_B could keep track of the time and just call METHOD_A when 5 seconds have passed since the previous call.
For what it's worth though I don't think that NSTimer will slip, so when you are updating the time you are probably doing something like time=time+interval, where it might make more sense to do (currentTime-startingTime)%interval, and then the synchronization shouldn't be a problem

Objective-C iPhone check location periodically

My iOS application relies heavily on GPS and I tried writing a method that helps conserve battery but I am having little success.
I created an NSTimer that fired every 15 seconds. Every time the method was called, it would increment an int time up by 1. If int time reached 20(5 minutes) it would turn off the location updates and set a bool isStopped to true. Every time the method ran and int time was above 20, it would increment another int, int time2, up by 1. If the method was ran and int time2 was equal to 4, it would start the location updates again and set time2 to 0.
Then in the didUpdateLocation: method for the location manager, I have an algorithm that would first check if the bool isStopped was true, if it was true then it would check the new location's horizontal accuracy and make sure it was under 10. Then it would check the newLocation with a location object named coords and check to see if they were greater than 9 meters apart. If they were not, it would stop location updates again and return. If they were, it would continue to another algorithm where it would check the new location object against some arguments. If it passed the coords location object would be set with the new location object, the time and time2 ints would be set to 0, the isStopped would be set to false, and the whole process would start all over again.
In short, after 5 minutes of no location changes, the location updates would be stopped and periodically checked every 1 minute to see if the user had moved at least 10 meters from the previous location that passed all requirements. When the user does move far enough, it starts the process all over again and the user has to not move 10 or more meters for 5 minutes before it starts the periodic checks. The thought behind this is to do only few second checks every minute when the user isn't moving much instead of constantly having the location services running.
Now here's the problem I run into, when the location updates stop. The NSTimer stops running while the app is in the background.
Could I somehow schedule a background task to run the loop between the 1 minute checks? Does anyone have any better ideas? Or any ideas on solutions to this?
A while ago I asked a question that features all the different ways that you can run GPS in the background.
CLLocationManager geo-fencing/startMonitoringForRegion: vs. startMonitoringForSignificantLocationChanges: vs. 10-minute startUpdating calls
You have to do specific things in order to maintain GPS in the background. A NSTimer would not suffice, since you need to register your app to be allowed to keep it running in the background after ten minutes. You minimally have to run the GPS every 10 minutes in the background to keep your app running.
Anyway, the methods in the above post should answer your question.

How to giva a time accurate timer in Fire Monkey?

I have to display a timer in 10th second for a sport competition. I have do this using the OnTimer event of a TTimer. the interval is set to 100. My routine display the current min:sec.10th (ex.: 02:45.7 ) correctly but it seem that my timer loose about 4 second at each minutes if I comp. to normal clock.
There is a better way to get a time accuracy timer in Delphi XE2 (or XE3) ?
You can use a timer to display the current value of the clock, but use a different approach to calculate the elapsed time.
You have to know that Windows timers are not time accurate, and even if you set it to elapse every 100 milliseconds, it can take more to fire the OnTimer event and even it can miss some intervals if for some reason elapses two or more times before your application process it.
You can, for example, use the system high-resolution performance counter to track times with nano-second accuracy.
You can also use the Delphi TStopwatch class, which encapsulates the system calls and falls back to other method (GetTickCount) if the high resolution performance counter is not available in your machine.
Take also a look at the How to Accurately Measure Elapsed Time Using High-Resolution Performance Counter delphi.about.com article.

Resources