2017-05-30 180 views
0

在iOS系统应用程序时钟,当我启动计时器或秒表,退出应用程序,杀死并重新打开它,计时器或秒表仍在运行。在后台运行计时器

怎样才可以有一个timer在后台运行?
并没有苹果是怎么做到的?

+0

您需要的时候你的应用程序再次运行重启定时器。 – rmaddy

+0

保存秒表或定时器响起的时间,然后计算花“在后台”再次打开该应用时设置新值的时间。 – LinusGeffarth

+0

他们需要它的地方写的(如'NSUserDefaults')一个'time_start',他们可以简单地继续重新启动后。 –

回答

1

这是可能的。
像这样:var bgTask = UIBackgroundTaskIdentifier()

这里是如何使用它:

var bgTask = UIBackgroundTaskIdentifier() 
    bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { 
     UIApplication.shared.endBackgroundTask(bgTask) 
    }) 
    let timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(notificationReceived), userInfo: nil, repeats: true) 
    RunLoop.current.add(timer, forMode: RunLoopMode.defaultRunLoopMode) 

我希望这将是有益的!

-1

关闭应用程序时,将当前计时器和时钟值存储在UserDefault内的长属性中,以秒或毫秒为单位。我使用的是通用的一个我可以分享:

static let userDefaults = UserDefaults.standard 

    public static func set<T: Hashable> (withValue value: T, andKey key: String) { 
     userDefaults.set(value, forKey: key) 
     userDefaults.synchronize() 
    } 
    public static func get(forKey key: String) -> Any? { 
     if((userDefaults.object(forKey: key)) != nil){ 
      let data = userDefaults.object(forKey: key) as? Any 
      return data 
     } 
     return nil 
    } 

当你再次启动应用程序,使用“get”方法来获得;可以说秒和存储时间。然后你可以比较当前时间到一个存储和计算之间的秒数,并添加时间差到存储秒,你可以设置定时出现的值,并保持下去。

这里是你如何设置它,当你关闭应用程序:通过标识在后台运行的请求令牌

NotificationCenter.default.addObserver(self, selector: #selector(storeTime), name: NSNotification.Name.UIApplicationWillResignActive, object: nil) 

func storeTime() { 
    "UserDefaultClassName".set(withValue: "preferably dictionary", andKey: String) 
}