迅速维持生计的最佳方法

时间:2019-05-21 17:45:05

标签: swift keep-alive

我的应用程序保持活动状态,即用户登录时开始保持活动状态,如果用户未与该应用程序交互,则该应用程序会发出警告,提示“只有2分钟,请关闭会话或继续” ,如果用户选择继续,则保持活动将重置;如果用户选择“关闭会话”,则保持活动将停止。

我使用计时器保持生命 警告计时器 计时器完成

两者都是在用户登录时开始的,区别在于每次执行的时间是2分钟。

重置保持活动状态时,该过程会使计时器无效并重新启动

当保持活动停止时,只有计时器无效。

当应用程序传递到后台并返回第一架飞机时,我使用通知中心,通过此功能,我可以重新计算时间以更新计时器的时间

notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appMovedToFront), name: UIApplication.didBecomeActiveNotification, object: nil)    


 @objc func appMovedToBackground() {
    keepAlive.sharedInstance.stopKeep()
}

/// When the app did become active the app sends the update time to front
@objc func appMovedToFront() {
    //LocationService.sharedInstance.region()
    if start != nil
    {
        let elapsed = CFAbsoluteTimeGetCurrent() - start
        time = time + Int(elapsed)
        keepAlive.sharedInstance.setTimes(timeWarning: arrTimes[0] - time, timeFinish: arrTimes[1]-time)
        keepAlive.sharedInstance.startKeep()
        if arrTimes[0] - time < 0 && flagLateWarning == false
        {
            keepAlive.sharedInstance.warningKeepAlive()
            flagLateWarning = true
        }
        let updateTime = arrTimes[1]-time
        let jsonObject: [String: Any] = [
            "time": updateTime,
            ]
        Backbase.publishEvent("update:Time", payload: jsonObject as? [String : NSObject])
        time = 0
    }
}



func stopKeep()
{
    timerWarning.invalidate()
    timerFinish.invalidate()
}

func startKeep()

    {
        if timeWarning > 0
        {
            timerWarning = Timer.scheduledTimer(timeInterval:     TimeInterval(timeWarning), target: self, selector:     #selector(warningKeepAlive), userInfo: nil, repeats: false)
        }
        if timeFinish > 0
        {
            timerFinish = Timer.scheduledTimer(timeInterval: TimeInterval(timeFinish), target: self, selector: #selector(finishKeepAlive), userInfo: nil, repeats: false)
        }
    }

func updateTimes(timePast: Int)
{
    timeWarning = timeWarning - timePast
    timeFinish = timeFinish - timePast
}

保持生命有效,但是老实说我不喜欢它,您是否有实现它的另一个想法?有时计时器会失败

0 个答案:

没有答案