AppDelegate.swift 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import UIKit
  2. import Flutter
  3. @UIApplicationMain
  4. @objc class AppDelegate: FlutterAppDelegate{
  5. var bgTask: UIBackgroundTaskIdentifier!
  6. override func application(
  7. _ application: UIApplication,
  8. didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  9. ) -> Bool {
  10. GeneratedPluginRegistrant.register(with: self)
  11. return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  12. }
  13. //app进入后台
  14. override func applicationDidEnterBackground(_ application: UIApplication){
  15. //开启后台任务保活
  16. comeToBackgroundMode()
  17. }
  18. func comeToBackgroundMode() {
  19. //初始化一个后台任务BackgroundTask,这个后台任务的作用就是告诉系统当前app在后台有任务处理,需要时间
  20. let app = UIApplication.shared
  21. bgTask = app.beginBackgroundTask(expirationHandler: { [self] in
  22. app.endBackgroundTask(bgTask)
  23. bgTask = UIBackgroundTaskIdentifier.invalid
  24. })
  25. //开启定时器 不断向系统请求后台任务执行的时间
  26. let timer = Timer.scheduledTimer(timeInterval: 30.0, target: self, selector: #selector(applyForMoreTime), userInfo: nil, repeats: true)
  27. timer.fire()
  28. }
  29. @objc func applyForMoreTime() {
  30. //如果系统给的剩余时间小于60秒 就终止当前的后台任务,再重新初始化一个后台任务,重新让系统分配时间,这样一直循环下去,保持APP在后台一直处于active状态。
  31. if UIApplication.shared.backgroundTimeRemaining < 60 {
  32. UIApplication.shared.endBackgroundTask(bgTask)
  33. bgTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { [self] in
  34. UIApplication.shared.endBackgroundTask(bgTask)
  35. bgTask = UIBackgroundTaskIdentifier.invalid
  36. })
  37. }
  38. }
  39. }