一旦设备连接到 wifi,我需要在我的应用程序中做一些事情。它不是关于“它连接到 wifi 了吗?”,而是“告诉我设备何时连接到 wifi,而之前它是离线的?”
换句话说,当 iPhone 以任何方式连接到互联网时,我需要响应事件。
AFNetworking
或自定义 API 是否可行?
最佳答案
您可以使用 Reachability .
在示例代码中您会发现:
import UIKit
let useClosures = false
class ViewController: UIViewController {
@IBOutlet weak var networkStatus: UILabel!
let reachability = Reachability.reachabilityForInternetConnection()
override func viewDidLoad() {
super.viewDidLoad()
if (useClosures) {
reachability?.whenReachable = { reachability in
self.updateLabelColourWhenReachable(reachability)
}
reachability?.whenUnreachable = { reachability in
self.updateLabelColourWhenNotReachable(reachability)
}
} else {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)
}
reachability?.startNotifier()
// Initial reachability check
if let reachability = reachability {
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
deinit {
reachability?.stopNotifier()
if (!useClosures) {
NSNotificationCenter.defaultCenter().removeObserver(self, name: ReachabilityChangedNotification, object: nil)
}
}
func updateLabelColourWhenReachable(reachability: Reachability) {
if reachability.isReachableViaWiFi() {
self.networkStatus.textColor = UIColor.greenColor()
} else {
self.networkStatus.textColor = UIColor.blueColor()
}
self.networkStatus.text = reachability.currentReachabilityString
}
func updateLabelColourWhenNotReachable(reachability: Reachability) {
self.networkStatus.textColor = UIColor.redColor()
self.networkStatus.text = reachability.currentReachabilityString
}
func reachabilityChanged(note: NSNotification) {
let reachability = note.object as! Reachability
if reachability.isReachable() {
updateLabelColourWhenReachable(reachability)
} else {
updateLabelColourWhenNotReachable(reachability)
}
}
}
关于ios - 如何检测 iPhone 是否刚刚连接到互联网?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32905132/