我有一个带有处理TCP通信的ObservedObject的SwiftUI工作表视图,当该工作表被解散时,我需要它发送最后一个tcp消息,然后关闭套接字。该onDisappear事件似乎永远不会被触发(编辑:发现了罪魁祸首它,因为我提出用板材UIHostingController,仍然需要一个解决方案),我想把它我的形式,导航视图,尝试创建一个新的堆栈为此,没有任何效果。因此,我尝试使用ObservedObject deinit进行尝试,但是如果我尝试在关闭视图后快速重新打开视图,则会出现访问错误。
deinit {
let msg = getUpdatedTimersString()
self.connection.sendMsg(msg, success: connection.close)
}
从我使用的连接类 Network Framework
func sendMsg(_ message: String, success: @escaping () -> Void = { }, error: @escaping () -> Void = { }) {
let msg = message + "\r\n"
let data: Data? = msg.data(using: .utf8)
debugPrint("Sending: \(msg)")
connection.send(content: data, completion: .contentProcessed { (sendError) in
if let sendError = sendError {
self.debug("\(sendError)")
error()
} else {
success()
}
})
}
func close() {
connection.cancel()
}
编辑:在下面添加视图代码
struct ScheduleView: View {
@ObservedObject var scheduleManager = ScheduleManager() // This handles the tcp communication, the deinit you see above is from this
var body: some View {
NavigationView {
Form {
ForEach(scheduleManager.timers) { timer in
ScheduleForm(scheduleManager: self.scheduleManager, timer: timer).onDisappear { debugPrint("schedule form row disappeared") } // This is just a view that adds a section header and a DatePicker to the form for each timer
}
}.onDisappear { debugPrint("form disappeared") }
.navigationBarTitle(Text("Schedule"), displayMode: .inline)
}.onDisappear() { debugPrint("nav disappeared") }
}
}
这些onDisappear都不适合我,ScheduleForm 行中的那个是唯一触发我的,但它会在创建工作表时以及每次我滚动看不见的行时触发,但不会在我关闭工作表时触发。
解:
final class ScheduleController: UIHostingController<ScheduleView> {
required init?(coder: NSCoder) {
super.init(coder: coder, rootView: ScheduleView())
}
init() {
super.init(rootView: ScheduleView())
}
override func viewWillDisappear(_ animated: Bool) {
rootView.scheduleManager.updateTimers() // this sends the last message
}
override func viewDidDisappear(_ animated: Bool) {
rootView.scheduleManager.connection.close // this closes the connection
}
}