我正在开发一个需要互联网连接才能正常运行的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.
}
}
答案 0 :(得分:0)
代替警报,最好使用隐藏的标签,并且在没有互联网时将其隐藏。然后在连接恢复后再次隐藏