【发布时间】: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