斯威夫特:我怎样才能让一个监听器报告连接何时丢失以及何时恢复?
Posted
技术标签:
【中文标题】斯威夫特:我怎样才能让一个监听器报告连接何时丢失以及何时恢复?【英文标题】:Swift: How can I have a listener that reports when connection is lost and when it comes back? 【发布时间】:2015-11-23 19:17:53 【问题描述】:我想在我的 ios 应用程序启动时调用一个方法,但我只想在有连接时调用这个方法。我发现在Objective-C中你可以使用Reachable
,但事实证明这个方法不是Swift的一部分。
我找到了一个名为 Reachability.swift 的 pod,我正在使用提供的示例:
override func viewWillAppear(animated: Bool)
let reachability: Reachability
do
reachability = try Reachability.reachabilityForInternetConnection()
catch
print("Unable to create Reachability")
return
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reachabilityChanged:",
name: ReachabilityChangedNotification,
object: reachability)
do
try reachability.startNotifier()
catch
print("This is not working.")
return
func reachabilityChanged(note: NSNotification)
let reachability = note.object as! Reachability
if reachability.isReachable()
if reachability.isReachableViaWiFi()
print("Reachable via WiFi")
else
print("Reachable via Cellular")
else
print("Not reachable")
但是,这不能正常工作。我只在进入那个 ViewController 时工作,而不是在我打开和关闭 WiFi 时工作。
【问题讨论】:
【参考方案1】:我已经通过将reachability
声明为 ViewController 的实例变量来解决这个问题:
var reachability: Reachability!
所以这个变量应该从方法viewWillAppear
中删除。
斯威夫特 2
override func viewWillAppear(animated: Bool)
do
reachability = try Reachability.reachabilityForInternetConnection()
catch
print("Unable to create Reachability")
return
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reachabilityChanged:",
name: ReachabilityChangedNotification,
object: reachability)
do
try reachability.startNotifier()
catch
print("This is not working.")
return
func reachabilityChanged(note: NSNotification)
let reachability = note.object as! Reachability
if reachability.isReachable()
if reachability.isReachableViaWiFi()
print("Reachable via WiFi")
else
print("Reachable via Cellular")
else
print("Not reachable")
Swift 3(由Burning提供)
var reachability: Reachability!
override func viewWillAppear(_ animated: Bool)
super.viewWillAppear(animated)
reachability = Reachability()
NotificationCenter.default.addObserver(self, selector: #selector(self.reachabilityChanged(_:)), name: Notification.Name.reachabilityChanged, object: reachability)
do
try reachability?.startNotifier()
catch
print("This is not working.")
return
func reachabilityChanged(_ note: NSNotification)
let reachability = note.object as! Reachability
if reachability.connection != .none
if reachability.connection == .wifi
print("Reachable via WiFi")
else
print("Reachable via Cellular")
else
print("Not reachable")
这工作正常:)。
【讨论】:
嘿,我尝试将其用于我的项目,但似乎在 swift 3 .reachabilityForInternetConnection() 中无法识别:您能帮我解决一下吗?以上是关于斯威夫特:我怎样才能让一个监听器报告连接何时丢失以及何时恢复?的主要内容,如果未能解决你的问题,请参考以下文章
我怎样才能让 2 个 wavefilereader 依次播放?