ios - 如何在没有网络连接的情况下持续出现警报?

标签 ios swift uialertview reachability reachability-swift

我正在开发一个需要互联网连接才能正常运行的 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.
}
}

最佳答案

与其使用警报,不如使用隐藏的标签,并且在没有互联网时不隐藏标签。连接恢复后再次隐藏

关于ios - 如何在没有网络连接的情况下持续出现警报?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51521580/

相关文章:

ios - 使用 IOS Accelerate Framework 对非二次幂图像进行二维信号处理?

iphone - JSON响应编码问题

ios - 在 Swift 中,Array [String] 切片返回类型似乎不是 [String]

ios - 从 Custom Payload Swift 获取数据

iphone - iPhone 的简单图形绘制任务

swift - 扩展 NSLayoutAnchor 编译错误

ios - 尽管图像很大,但 UIImageView 在 UICollectionViewCell 中显得很小

ios - UIAlertView 改变背景颜色

ios - 以 10 : in swift 2 为基数的 int () 的无效文字面临错误

ios - 从 iOS 8 中的 UIAlertView 移除 alpha