swiftui - 当应用程序处于后台时如何控制`Timer.publish()`
问题描述
我目前正在使用 SwiftUI 开发应用程序。
我正在尝试制作一个计时器应用程序,并且我想Timer.publish()
在应用程序在后台时控制方法。
在我的应用程序中,当应用程序进入时,我需要继续Timer.publish()
计算一个数字active
,background
因此我进行了如下设置:
-
- 打开项目文件
-
- 添加的能力
Background Modes
- 添加的能力
-
- 检查
Audio, Airplay, and Picture in Picture
我附上的图片
- 检查
Timer.publish()
仅当我将 a 设置为时,我才想继续在后台running
工作timerStatus
,但就我的代码而言,即使我选中stoped
,Timer.publish()
也在后台工作。
只有当我检查为时,我怎么能Timer.publish()
在后台running
工作timerStatus
?(我想在应用程序在后台时onRecieve
通过方法消失并设置为)print
stoped
timerStatus
以下是代码:
内容视图.swift
import SwiftUI
struct ContentView: View {
@Environment(\.scenePhase) private var scenePhase
var timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var timerStop = Timer()
@State var appStatus: AppStatus = .active
@State var timerStatus: TimerStatus = .running
@State var counter = 0
var body: some View {
VStack{
HStack{
Text("RUN")
.onTapGesture {
timerStatus = .running
}
Text("STOP")
.onTapGesture {
timerStatus = .stoped
}
}
Text(timerStatus == .running ? "running" : "stoped")
.padding()
Text(String(counter))
.padding()
}
.onChange(of: scenePhase) { phase in
switch phase {
case .active:
appStatus = .active
case .inactive:
appStatus = .inactive
case .background:
appStatus = .background
default:
break
}
}
.onReceive(timer) { _ in
print("onRecieve")
if timerStatus == .running{
counter += 1
}
}
}
}
enum AppStatus {
case active
case inactive
case background
}
enum TimerStatus {
case running
case stoped
}
TimerControlApp.swift
import SwiftUI
@main
struct TimerControlApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
Xcode:版本 12.0.1
iOS:14.0
生命周期:SwiftUI 应用
解决方案
推荐阅读
- javascript - 在从用户那里获得特定的 CSS 代码后重新加载 index.js
- android-studio - 安卓。录制视频时覆盖的 Surface 闪烁
- performance - 在 Jmeter 的另一个变量中传递变量
- c# - C# 对路径的访问被拒绝...(System.UnauthorizedAccessException:对路径“C:\”的访问被拒绝。)
- java - CSV 数据配置未向 HTTP 请求发送数据
- javascript - 为什么这个函数不执行任何操作?
- python - 未找到 Web Scraping Div 类
- php - 如何设置 Backpack Crud 生成器创建类 CamelCase
- android - 无法修复:找不到 kotlin-reflect-1.3.72.jar (org.jetbrains.kotlin:kotlin-reflect:1.3.72)
- c++ - 在桌面屏幕上叠加文本和图形(描边矩形)