【问题标题】:How to continuously appear alert while there is no internet connection?如何在没有互联网连接的情况下持续显示警报?
【发布时间】:2018-07-25 14:35:33
【问题描述】:

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

【问题讨论】:

  • 我认为更好的做法是在由于缺乏互联网连接而实际失败时显示“重试”警报 - 您可以处理来自网络框架的回调。
  • 很抱歉,您能说得更直白一点吗?我知道,根据我的阅读,最好的做法是仅在无法访问 REST api 时发出警报,但对于这种特殊情况,我希望它自动警告用户他没有连接。我希望该警报在没有连接时继续显示。
  • 不管你的应用在做什么,如果没有连接,你的网络请求将会失败。所以这是处理缺少连接错误的地方。
  • 问题是它不会失败。它继续运行,但没有出现应该显示的内容。

标签: ios swift uialertview reachability reachability-swift


【解决方案1】:

最好使用隐藏的标签而不是警报,而在没有互联网的情况下不隐藏标签。然后在连接恢复后再次隐藏

【讨论】:

  • 好的!我喜欢这个主意!一旦我尝试过,我会回复你的!非常感谢,但我有一个问题。我喜欢警报的一件事是用户无法访问背景。有没有使用标签从后台“阻止”用户?
  • 您可以添加一个屏幕大小的按钮来覆盖屏幕。它还会拦截任何点击(您不需要对点击做任何事情,只需接收点击事件)。您可以将按钮设置为 50% 透明,以提供与警报类似的效果。在按钮顶部,您可以在消息中添加标签。按钮和标签都根据网络连接出现/消失
猜你喜欢
  • 1970-01-01
  • 2016-11-27
  • 1970-01-01
  • 1970-01-01
  • 2015-08-25
  • 2018-01-31
  • 2017-08-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多