簡體   English   中英

沒有互聯網連接時如何連續顯示警報?

[英]How to continuously appear alert while there is no internet connection?

我正在開發一個需要互聯網連接才能正常運行的iOS應用,因此我正在使用“可達性”框架,以便獲得連接狀態。 現在,只要我沒有互聯網連接,就會出現一次提示“再次嘗試”的按鈕,然后提醒我,這是警報,該提示將在沒有互聯網的情況下持續出現。 你能幫我嗎? 謝謝!

順便說一句,如果您認為有什么事情我應該改變,那就告訴我! 干杯!

class ViewController: UIViewController {

let reachability = Reachability()!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func viewDidAppear(_ animated: Bool) {

    reachability.whenReachable = { reachability in
        if reachability.connection == .wifi {
            print("Reachable via WiFi")
        } else {
            print("Reachable via Cellular")
        }
    }
    reachability.whenUnreachable = { _ in
        print("Not reachable")
    }

    do {
        try reachability.startNotifier()
    } catch {
        print("Unable to start notifier")
    }

    NotificationCenter.default.addObserver(self, selector: #selector(reachabilityChanged(note:)), name: .reachabilityChanged, object: reachability)
    do{
        try reachability.startNotifier()
    }catch{
        print("could not start reachability notifier")
    }
}

@objc func reachabilityChanged(note: Notification) {

    let reachability = note.object as! Reachability

    switch reachability.connection {
    case .wifi:
        print("Reachable via WiFi")
    case .cellular:
        print("Reachable via Cellular")
    case .none:
        print("Network not reachable")
        createAlert(title: "No Internet Connection", message: "Internet Connection is required fot this application to run properly")
    }
}

func createAlert(title:String, message:String)
{
    let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.alert)

    alert.addAction(UIAlertAction(title: "Try Again", style: UIAlertActionStyle.default, handler: { (action) in alert.dismiss(animated: true, completion: nil) } ) )

    self.present(alert, animated: true, completion: nil)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

最好使用隱藏且在沒有互聯網時不隱藏的標簽來代替警報。 連接恢復后再隱藏

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM