2016-12-10 39 views
1

我想解僱視圖控制器,如果互聯網連接。當沒有互聯網它呈現我的noInternetViewController,但是當我重新連接到互聯網,noInternetViewController視圖沒有解僱。如何解除視圖控制器如果互聯網連接

override func viewWillDisappear(_ animated: Bool) { 
    super.viewWillDisappear(animated) 

    NotificationCenter.default.removeObserver(self, name: ReachabilityChangedNotification, object: reachability) 
} 

func reachabilityChanged(note: NSNotification) { 
    let reachability = note.object as! Reachability 

    if reachability.isReachable { 
     if noInternet == true { 
      DispatchQueue.main.async { 
       self.noInternet = false 
       self.dismiss(animated: true, completion: nil) 
      } 
     } 
    } else { 
     noInternet = true 
     if noInternet == true { 
      DispatchQueue.main.async { 
       let storyboard = UIStoryboard(name: "Main", bundle: nil) 
       let noInternetViewController = storyboard.instantiateViewController(withIdentifier: "NoInternetViewController") as! NoInternetViewController 
       noInternetViewController.modalPresentationStyle = UIModalPresentationStyle.overFullScreen 
       self.present(noInternetViewController, animated: true, completion: nil) 
      } 
     } 

    } 
} 

而且NoInternetViewController:

import UIKit 

class NoInternetViewController: UIViewController { 

    override func viewDidLoad() { 
     super.viewDidLoad() 
    } 
} 

感謝您的幫助

+0

當noInternetViewController呈現,我重新連接後,reachabilityChanged(注意:NSNotification)func沒有觸發我認出。我認爲這是因爲removeObserver,但我找不到正確的方式來使用它。 – Brkr

+1

'noInternet = true;如果noInternet == true {'如果在上面的行中將其設置爲true,它將始終爲真。 BTW添加== true是多餘的 –

+0

您正在使用'self.dismissViewController',但您需要關閉noInternetComtroller;你可以在一個屬性中保留對提供的控制器的引用,而不是布爾型 – Paulw11

回答

1

在你NoInternetViewController,你可以一個Observer添加到它。當你收到連接時,發佈一個通知來觸發它的選擇器來解除它自己。

override func viewDidLoad() { 
    super.viewDidLoad() 
    NotificationCenter.default.addObserver(self, selector: #selector(receivedConnection), name: NSNotification.Name.init(rawValue: "ReceivedConnection"), object: nil) 
} 

func receivedConnection() { 
    self.dismiss(animated: true, completion: nil) 
} 
+0

感謝它現在正在工作 – Brkr