我在watchOS中创建了一个简单的倒计时计时器。当您按下start时,计时器启动,session.start也被声明。背景下一切都很好。然后,当它通过按钮或计时器停止时,会话将无效。
顺便说一下,我正在阅读这里的文档
它指出一次只能安排一个会话;如果需要重新安排会话,请使当前会话无效,然后安排一个新会话";
所以我的问题是,如何在SwiftUI中创建新会话这是我的代码:
import SwiftUI
struct TestView: View {
@State var start = false
@State var number = 10
@State var time = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var session = WKExtendedRuntimeSession()
var body: some View {
VStack {
Text("(number)")
Spacer()
Button(action: {
self.start.toggle()
if self.start {
session.start()
} else {
session.invalidate()
}
}) {
Text(self.start ? "Stop" : "Start")
}
}.onReceive(self.time) { (_) in
if self.start {
if number > 0 {
number -= 1
} else {
self.start.toggle()
number = 10
session.invalidate()
}
}
}
}
}
最好在课堂上进行,如Coordinator
class SessionCoordinator {
private var session: WKExtendedRuntimeSession?
func start() {
guard session?.state != .running else { return }
// create or recreate session if needed
if nil == session || session?.state == .invalid {
session = WKExtendedRuntimeSession()
}
session?.start()
}
func invalidate() {
session?.invalidate()
}
}
struct TestView: View {
let coordinator = SessionCoordinator()
@State var start = false
@State var number = 10
@State var time = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
VStack {
Text("(number)")
Spacer()
Button(action: {
self.start.toggle()
if self.start {
coordinator.start()
} else {
coordinator.invalidate()
}
}) {
Text(self.start ? "Stop" : "Start")
}
}.onReceive(self.time) { (_) in
if self.start {
if number > 0 {
number -= 1
} else {
self.start.toggle()
number = 10
coordinator.invalidate()
}
}
}
}
}