首页 > 解决方案 > 当应用程序处于后台时如何控制`Timer.publish()`

问题描述

我目前正在使用 SwiftUI 开发应用程序。

我正在尝试制作一个计时器应用程序,并且我想Timer.publish()在应用程序在后台时控制方法。

在我的应用程序中,当应用程序进入时,我需要继续Timer.publish()计算一个数字activebackground因此我进行了如下设置:

在此处输入图像描述

Timer.publish()仅当我将 a 设置为时,我才想继续在后台running工作timerStatus,但就我的代码而言,即使我选中stopedTimer.publish()也在后台工作。

只有当我检查为时,我怎么能Timer.publish()在后台running工作timerStatus?(我想在应用程序在后台时onRecieve通过方法消失并设置为)printstopedtimerStatus


以下是代码:

内容视图.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 应用

标签: swiftui

解决方案


推荐阅读