【问题标题】:Go back to previous controller from class swift从 swift 类返回上一个控制器
【发布时间】:2015-09-03 15:40:18
【问题描述】:

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

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

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

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

谢谢

【问题讨论】:

    标签: ios swift class uinavigationcontroller


    【解决方案1】:

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

    navigationController?.popViewControllerAnimated(true)
    

    如果你需要在视图控制器中而不是在另一个类中使用这个函数,你可以使用 NSNotificationCenter 来通知视图控制器,当它需要显示前一个控制器时,就像这样:

    YourViewController

    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 和委托之间的区别,我向您推荐 this answer

    【讨论】:

    • 工作得很好,当涉及到控制器和类之间的通信时,通知似乎是处理所有事情的方法。谢谢!
    • 你真的应该为此使用委托。
    【解决方案2】:

    除了 NSNotificationCenter 之外,一种常见的方法是利用闭包或委托来通知您的 ViewController 流式传输尝试失败。使用闭包,负责流式传输的类的 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
            }
        })
    }
    

    【讨论】:

      猜你喜欢
      • 2015-05-13
      • 2020-08-18
      • 1970-01-01
      • 2017-05-26
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多