1
我有一些任務需要異步執行。所以我正在創建一個類的dispatchqueue並執行一些任務。在swift中使用NotificationCenter停止Dispatchqueue 3
//Adding Observer
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification).
。
//Creating Background Thread.
let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
//Asynch thread.
anotherQueue.async {
for i in 0..<50 {
print("\n ",i)
sleep(1)
}
}
但在一些事件中,我想停止這個,並且正在處理類似這樣的事情。
func catchNotification (notification:Notification) -> Void {
//Stop the queue.
anotherQueue.suspend()
}
我發佈了一些其他類的通知。通知正在收到。但線程沒有被暫停。
這是完整的類,如果你想參考。
LoginPresenter.swift
let anotherQueue = DispatchQueue(label: "Thread1", qos: .background)
class LoginPresenter : LoginInteractor {
func catchNotification (notification:Notification) -> Void {
//Stop the queue.
anotherQueue.suspend()
}
func LoginSuccessFull()
{
NotificationCenter.default.addObserver(forName: NSNotification.Name(rawValue: "NotificationIdentifier"), object: nil, queue: nil, using:catchNotification)
//Asynch thread.
anotherQueue.async {
//Synch
for i in 0..<50 {
print("\n ",i)
sleep(1)
}
}
}
,或者任何其他更好的方法或機制是否有這樣做嗎?
取而代之,您可以在登錄屏幕上向用戶顯示ActivityView,然後一旦您收到通知就停止並關閉viewController。 –
停止發生在通話結束後任何程序段運行完成後。這是在https://developer.apple.com/reference/dispatch/dispatchobject/1452801-suspend中寫的內容。 –