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中写的内容。 –