从 class swift 返回上一个控制器

Go back to previous controller from class swift

我有一个应用程序使用 http 调用从外部存储流式传输视频。 当用户的设备未连接到网络服务时,我需要应用程序返回到之前的控制器。

流程如下:用户访问元素列表(table 视图单元格),select 一个,然后应用程序转到播放器控制器。在此控制器上,调用流式传输文件。

我在控制器外部的 class 中使用 api 调用处理程序,但我不知道如何继续让它从这里返回到之前的控制器(元素列表).

连接问题错误都在 api class 中捕获。 我没有显示任何代码,因为我不确定它是否相关。如果您需要查看任何内容,请告诉我,我会更新问题。应该怎么做呢? (当然我用的是导航控制器)

谢谢

如果你想回到之前的视图控制器,你应该使用:

navigationController?.popViewControllerAnimated(true)

如果您不需要在视图控制器中使用此功能,而是在另一个 class 中使用,您可以使用 NSNotificationCenter 在需要时通知视图控制器显示之前的控制器,就像这样:

你的ViewController

override func viewDidLoad() 
{
    ...

    NSNotificationCenter.defaultCenter().addObserver(
        self,
        selector: "goBack:",
        name: "goBackNotification",
        object: nil)

    ...
}

func goBack(notification: NSNotification)
{
    navigationController?.popViewControllerAnimated(true)
}

另一个类

NSNotificationCenter.defaultCenter().postNotificationName("goBackNotification", object: nil)

不要忘记在 YourViewController:

中删除观察者
deinit 
{
    NSNotificationCenter.defaultCenter().removeObserver(self)
}

编辑 1: 您显然可以使用 delegate 而不是 NSNotification 方法。如果你不知道 NSNotification 和 delegate 的区别我推荐给你 this answer.

除了 NSNotificationCenter 之外的一种常见方法是利用闭包或委托来通知您的 ViewController 流式传输尝试失败。使用闭包,负责流式传输的 class 的 API 可以扩展为将完成闭包作为参数,并在发生时使用 NSError 调用它,如果没有发生则使用 nil 调用它。

func streamFile(completion: NSError? -> Void) {
    // Try to start the streaming and call the closure with an error or nil
    completion(errorOrNil)
}

当调用 ViewController 中的 API 时,您可以将闭包传递给该方法并检查错误。如果出现问题,应该出现错误并且 ViewController 应该被忽略

func startStream() {
    StreamingAPIClient.streamFile(completion: { [weak self] error in
        if error != nil {
            // Handle error
            self.dismissViewControllerAnimated(true, completion: nil)
        } else {
            // Proceed with the streaming
        }
    })
}