ios - Run defined time using NSTimer as a clock -


i have been struggling time nsdate run (as in clock) unfortunately it's not easy think. yes did google haven't been able find solid solution.

here's i'm doing. current date , time api because cannot rely on local date time since can altered via settings. therefore get current date , time api , using date formatter proper format , assign nstimer , nsrunloop run clock , update in label every second.

the issue that, way have implemented it, feel since date i've assigned firedate maybe different local time , becomes mismatch in time, loop works according local date time no matter output api. feel run future date please me out , code written given below. thanks.

let timeinterval: nstimeinterval = 1.0 var dateformatter = nsdateformatter() dateformatter.timezone = nstimezone(name: "gmt")  let servernowdate: nsdate! = dateformatter.datefromstring(datetime.servernow())! println("2015-07-21 11:06:31 am")  var timer = nstimer(firedate: servernowdate, interval: timeinterval, target: self, selector: selector("updatetimer:"), userinfo: nil, repeats: true)   func updatetimer(timer:nstimer!) //this doesn't called {         var dateformatter = nsdateformatter()         dateformatter.dateformat = "hh:mm a"         dateformatter.timezone = nstimezone(name: "gmt") } 

the reason why timer doesn't fire because it's not scheduled. need tell nstimer on runloop run on. convenience apple provided method return scheduled timer:

class func scheduledtimerwithtimeinterval(_ seconds: nstimeinterval,                                    target target: anyobject,                                  selector aselector: selector,                                  userinfo userinfo: anyobject?,                                   repeats repeats: bool) -> nstimer 

additionall want say:

this won't intend. think wan't display clock 'real date', there no code accomplish that.

to save time this: https://github.com/jbenet/ios-ntp

this give reliable time information , nice access current date & time.

finally want tell you shouldn't instantiate dateformatters inside fire method, since pretty heavy object create , impact performance negatively. should create once , keep using same instance.


Comments