[英]Go back to previous controller from class swift
我有一個應用程序,它使用 http 調用從外部存儲傳輸視頻。 當用戶的設備未連接到網絡服務時,我需要應用程序返回到之前的控制器。
流程如下:用戶訪問元素列表(表格視圖單元格),選擇一個,然后應用程序轉到播放器控制器。 在此控制器上,調用以流式傳輸文件。
我在控制器外部的類中使用了 api 調用處理程序,但我不知道如何繼續使其從這里(元素列表)返回到前一個控制器。
連接問題錯誤都在 api 類中捕獲。 我沒有顯示任何代碼,因為我不確定它是否相關。 如果您需要查看任何內容,請告訴我,我會更新問題。 應該用什么方法來做到這一點? (當然我使用導航控制器)
謝謝
如果你想回到之前的視圖控制器,你應該使用:
navigationController?.popViewControllerAnimated(true)
如果您不需要在視圖控制器中而是在另一個類中使用此功能,則可以使用NSNotificationCenter在需要顯示前一個控制器時通知視圖控制器,就像這樣:
你的視圖控制器
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:您顯然可以使用委托而不是 NSNotification 方法。 如果您不知道 NSNotification 和 delegate 之間的區別,我向您推薦這個答案。
除了 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
}
})
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.