你怎么能 stop/cancel 在 Swift3 中回调?

How can you stop/cancel callback in Swift3?

在我的应用程序中,我有一个进行云调用的方法。它有一个完成处理程序。在某些时候,当用户向云发出此调用并在等待完成时,用户可能会点击注销。

这将从堆栈中删除控制器,因此完成块将 returned 到不再位于堆栈中的控制器。

这会导致崩溃,因为我在完成 return 时执行了一些 UI 任务。 我做了一个解决方法,我没有对 UI 做任何事情是控制器不再在堆栈上。

但是,我很好奇是否可以在注销时以某种方式cancel/stop所有挂起的回调?

为了精细控制操作的取消,您可以 return 从您的函数中取出一个取消标记。在需要取消操作时调用它。

这是一个如何实现的例子:

typealias CancellationToken = () -> Void

func performWithDelay(callback: @escaping () -> Void) -> CancellationToken {
    var cancelled = false
    // For the sake of example delayed async execution 
    // used to emulate callback behavior.
    DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
        if !cancelled {
            callback()
        }
    }
    return { cancelled = true }
}

let cancellationToken = performWithDelay {
    print("test")
}

cancellationToken()

对于您只需要确保在块执行中仍然满足所有必要的先决条件和条件的情况,您可以使用 guard:

  { [weak self] in 
    guard let `self` = self else { return }
    // Your code here... You can write a code down there 
    // without worrying about unwrapping self or 
    // creating retain cycles.
  }

我不确定,但我认为某些东西是紧密耦合的。尝试做:

{ [weak self] () -> Void in
            guard let _ = self else { return }
//rest of your code
}

如果您被取消初始化,那么您的 completioHanlder 将不会继续。