繁体   English   中英

Swift如何使用NSTimer背景?

[英]Swift how to use NSTimer background?

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:    Selector("update"), userInfo: nil, repeats: true)
    }

    func update() {
       println("Something cool")
    }
}

对于模拟器来说没关系,我会通过点击主页按钮获得连续的“Something cool”。 但是当我用我的iPhone调试应用程序时,它就解决了。 当我点击主页按钮并使我的应用程序运行背景时,我没有得到任何东西。 有人告诉我,我可以播放一段很长的空白音乐,让我的应用程序在后台运行。但我不知道如何用swift @matt在后台播放音乐

您可以使用beginBackgroundTaskWithExpirationHandler来获取一些后台执行时间。

class ViewController: UIViewController {
    var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

    override func viewDidLoad() {
        super.viewDidLoad()
        backgroundTaskIdentifier = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
            UIApplication.sharedApplication().endBackgroundTask(self.backgroundTaskIdentifier!)
        })
        var timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "update", userInfo: nil, repeats: true)
    }

    func update() {
        println("Something cool")
    }
}

Swift 3.0

backgroundTaskIdentifier = UIApplication.shared.beginBackgroundTask(expirationHandler: {
    UIApplication.shared.endBackgroundTask(self.backgroundTaskIdentifier!)
})

这段代码的灵感来自于这个答案 ,但我移植到了swift。

这显然只在iOS 7+上运行3分钟。

我愿意打赌你不需要在后台运行计时器,你需要知道你被暂停时已经过去的时间。 这比使用空声音文件更好地利用您的资源。

使用applicationWillResignActiveapplicationDidBecomeActive确定已经过了多长时间。 首先保存计时器的fireDate,并在applicationWillResignActive使其无效

func applicationWillResignActive(application: UIApplication) {
    guard let t = self.timer else { return }
    nextFireDate = t.fireDate
    t.invalidate()
}

接下来,通过将现在的时间与您在applicationWillResignActive调用中保存的fireDate进行比较,确定applicationDidBecomeActive计时器的剩余时间:

func applicationDidBecomeActive(application: UIApplication) {
    guard let n = nextFireDate else { return }
    let howMuchLonger = n.timeIntervalSinceDate(NSDate())
    if howMuchLonger < 0 {
        print("Should have already fired \(howMuchLonger) seconds ago")
        target!.performSelector(selector!)
    } else {
        print("should fire in \(howMuchLonger) seconds")
        NSTimer.scheduledTimerWithTimeInterval(howMuchLonger, target: target!, selector: selector!, userInfo: nil, repeats: false)
    }
}

如果你需要一个重复的,只需要数学计算出计时器应该在后台触发多少次

let howManyTimes = abs(howMuchLonger) / repeatInterval

当我点击主页按钮并让我的应用程序运行背景

不,这是一个错误的假设。 当您点按主屏幕按钮时,您不会让您的应用在后台运行。 您可以在后台暂停您的应用。 当您在后台时,您的代码不会运行

应用程序可以获得在后台运行的特殊权限,以便执行某些有限的活动,例如继续播放音乐或继续使用Core Location。 但你的应用程序没有做任何事情,所以它进入后台并停止。

在appdelegate中添加此代码以在后台运行任务,其工作正常,

var backgroundUpdateTask: UIBackgroundTaskIdentifier = 0

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
    return true
}

func applicationWillResignActive(application: UIApplication) {
    self.backgroundUpdateTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler({
        self.endBackgroundUpdateTask()
    })
}

func endBackgroundUpdateTask() {
    UIApplication.sharedApplication().endBackgroundTask(self.backgroundUpdateTask)
    self.backgroundUpdateTask = UIBackgroundTaskInvalid
}

func applicationWillEnterForeground(application: UIApplication) {
    self.endBackgroundUpdateTask()
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM