gpt4 book ai didi

swift - 当 SwiftUI View 关闭时,如何发送最后一条消息并关闭套接字?

转载 作者:行者123 更新时间:2023-11-30 10:26:56 26 4
gpt4 key购买 nike

我有一个 SwiftUI 工作 TableView ,其中有一个 ObservedObject 处理 tcp 通信,当此工作表被关闭时,我需要它发送最后一条 tcp 消息,然后关闭套接字。 onDisappear 事件似乎永远不会被触发(编辑:找到罪魁祸首,因为我使用 UIHostingController 呈现工作表,仍然需要一个解决方案 )我尝试将其放在表单、导航 View 中,尝试为其创建一个新堆栈,但没有任何效果。因此,我尝试使用我的 ObservedObject deinit,但是如果我尝试在关闭 View 后快速重新打开 View ,这会给我带来严重的访问错误。

deinit {
let msg = getUpdatedTimersString()
self.connection.sendMsg(msg, success: connection.close)
}

来 self 使用 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()
}

编辑:添加下面的 View 代码

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
}
}

关于swift - 当 SwiftUI View 关闭时,如何发送最后一条消息并关闭套接字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59977120/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com