【发布时间】:2017-01-25 15:34:08
【问题描述】:
好的,所以我对 Swift 还很陌生,我对我正在尝试做的事情感到有些困惑,或者我是否走错了方向。 (https://github.com/ashleymills/Reachability.swift)
这是我的viewDidLoad 方法:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
checkConnection()
}
然后我有一个函数,其中包含来自 Reachability GitHub 项目的代码:
func checkConnection() {
//declare this property where it won't go out of scope relative to your listener
let reachability = Reachability()!
reachability.whenReachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
DispatchQueue.main.async {
if reachability.isReachableViaWiFi {
print("Reachable via WiFi")
} else {
print("Reachable via Cellular")
}
}
}
reachability.whenUnreachable = { reachability in
// this is called on a background thread, but UI updates must
// be on the main thread, like this:
DispatchQueue.main.async {
self.dim(direction: .In, alpha: self.dimLevel, speed: self.dimSpeed)
self.performSegue(withIdentifier: "mainToAlertNoInternet", sender: self)
}
}
do {
try reachability.startNotifier()
} catch {
print("Unable to start notifier")
}
}
如您所见,当没有互联网时,代码如下:
self.dim(direction: .In, alpha: self.dimLevel, speed: self.dimSpeed)
self.performSegue(withIdentifier: "mainToAlertNoInternet", sender: self)
Dim 取自 (http://www.totem.training/swift-ios-tips-tricks-tutorials-blog/ux-chops-dim-the-lights),mainToAlertNoInternet 以透明方式加载当前视图的下一个视图,因此它是一种警报样式。
所以,第二个 segue 上有一个视图和一个按钮。没有什么了不起的,这是没有互联网时加载的内容:
那个重试按钮链接到Segue的Exit并在First View Controller中运行这个功能:
@IBAction func unwindFromSecondary(segue: UIStoryboardSegue) {
dim(direction: .Out, speed: dimSpeed)
checkInternetConnection()
}
我在函数mainToAlertNoInternet中添加了这样当他们再次点击尝试时,它会回到第一个segue并再次运行测试。但是,当我再次单击尝试时,我收到此错误:
警告:尝试呈现不在窗口层次结构中的视图!
希望我已经对我的设置进行了足够的解释。现在回答问题:
1) 我该如何解决这个错误? 2) 我这样做是对的还是有更好的方法?
这就是我想要的:
我想在应用加载时检查互联网连接。如果没有连接,我想像我一直在做的那样显示 segue。如果用户单击 Try gain,我希望它返回到第一个控制器并再次运行检查,如果仍然没有连接,则像最初一样再次显示 segue。我希望这是一个重复的过程,直到有互联网。
感谢您的所有帮助。提前致谢
编辑:
我在 ViewDidAppear 方法中添加了函数调用,如下所示:
override func viewDidAppear(_ animated: Bool) {
checkInternetConnection()
}
但是,它没有运行。当我这样做时,unwindFromSecondary 函数中的 DIM 也不会被调用。
编辑 2:
刚刚将此行添加到我的viewDidAppear:
print("Appeared")
最初会调用它,但之后不会再次调用。
问题:
在 unwindSegue 之后再次加载所有内容后,如何让函数运行?
有什么想法吗?
更新 3
好的,所以我查看了以下答案:
@MarkP 答案工作正常。谢谢你 然而,@iSee 的回答让我想到也许我应该以不同的方式解决这个问题。
我在这篇文章中添加了一个赏金,以获得详细的答案,可以向我展示并解释如何实现以下目标:
在我的应用程序中。我需要继续确保在任何加载的视图上都存在互联网(可能是计时器)。我希望它像当前的方式一样,如果没有互联网,它将弹出带有此 segue 的 ViewController:
performSegue(withIdentifier: "mainToAlertNoInernet", sender: self)
App Delegate 似乎是这个地方,但我不确定如何实现这一点。
我是 iOS 开发的新手,因此希望得到一些解释和指导。
感谢您的宝贵时间。非常感谢。
【问题讨论】:
标签: ios swift reachability reachability-swift