Swiftui 如何在应用程序处于后台时控制'Timer.publish()'
我目前正在使用SwiftUI开发一个应用程序 我正在尝试制作一个计时器应用程序,我想在应用程序处于后台时控制Swiftui 如何在应用程序处于后台时控制'Timer.publish()',swiftui,Swiftui,我目前正在使用SwiftUI开发一个应用程序 我正在尝试制作一个计时器应用程序,我想在应用程序处于后台时控制timer.publish()方法 在我的应用程序中,我需要继续工作Timer.publish()在应用程序处于活动状态和背景状态时计算一个数字,因此我做了如下设置: 打开项目文件 添加后台模式的功能 检查音频、播放和图片中的图片作为我附加的图像 只有当我将正在运行的设置为timerStatus时,我才想继续在后台工作Timer.publish(),但对于我的代码,即使我
timer.publish()
方法
在我的应用程序中,我需要继续工作Timer.publish()
在应用程序处于活动状态和背景状态时计算一个数字,因此我做了如下设置:
-
- 打开项目文件
-
- 添加
后台模式的功能
-
- 检查
音频、播放和图片中的图片
作为我附加的图像
只有当我将正在运行的设置为timerStatus
时,我才想继续在后台工作Timer.publish()
,但对于我的代码,即使我选中了stopped
,Timer.publish()
在后台工作
只有当我选中作为timerStatus
运行时,我如何才能在后台工作Timer.publish()
?
(当应用程序在后台停止时,我想通过print
方法在接收时消失onreceive
,并将设置为timerStatus
)
代码如下:
ContentView.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应用程序