我正在尝试将网络连接检测集成到我的应用程序中,但是,由于我的网络更改未被检测到/打印到控制台中,因此我似乎在某处出错。
正如帖子中提到的,我目前正在使用以下类和工具来完成这项工作:
{.h, .m}
NSNotificationCenter
码
在AppDelegate.Swift中,我设置了NSNotificationCenter
来检测更改:
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// ...
// A: Checks if the device is connected to the internet
var defaultCenter: Void = NSNotificationCenter().addObserver(self, selector:"checkForReachability", name: kReachabilityChangedNotification, object: nil)
}
在同一个类AppDelegate
中,我还创建了这个函数,只要有变化就会触发:
func checkForReachability () {
var networkReachability = Reachability.reachabilityForInternetConnection()
networkReachability.startNotifier()
var remoteHostStatus = networkReachability.currentReachabilityStatus()
if (remoteHostStatus.value == NotReachable.value) {
println("Not Reachable")
} else if (remoteHostStatus.value == ReachableViaWiFi.value) {
println("Reachable via Wifi")
} else {
println("Reachable")
}
}
但是,当使用网络链接调节器来操作和模拟条件的变化时,我无法看到控制台中反映出的任何更改。任何帮助都会膨胀!
您必须先创建一个Reachability对象,然后才能从中接收通知。另外,请务必在您创建的Reachability对象上调用startNotifier()
方法。这将是您在应用程序委托中如何执行此操作的示例:
class AppDelegate: UIResponder, UIApplicationDelegate
{
private var reachability:Reachability!;
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
NSNotificationCenter.defaultCenter().addObserver(self, selector:"checkForReachability:", name: kReachabilityChangedNotification, object: nil);
self.reachability = Reachability.reachabilityForInternetConnection();
self.reachability.startNotifier();
}
@objc func checkForReachability(notification:NSNotification)
{
// Remove the next two lines of code. You cannot instantiate the object
// you want to receive notifications from inside of the notification
// handler that is meant for the notifications it emits.
//var networkReachability = Reachability.reachabilityForInternetConnection()
//networkReachability.startNotifier()
let networkReachability = notification.object as Reachability;
var remoteHostStatus = networkReachability.currentReachabilityStatus()
if (remoteHostStatus.value == NotReachable.value)
{
println("Not Reachable")
}
else if (remoteHostStatus.value == ReachableViaWiFi.value)
{
println("Reachable via Wifi")
}
else
{
println("Reachable")
}
}
}
我建议你看一下NSNotificationCenter和NSNotification的文档。这样你就会更熟悉下次出现这种情况时如何处理通知。
斯威夫特3
NotificationCenter.default.addObserver(self, selector:Selector(("checkForReachability:")), name: NSNotification.Name.reachabilityChanged, object: nil)
let reachability: Reachability = Reachability.forInternetConnection()
reachability.startNotifier()
根据@ Hardik.T更新了Swift 4
1.在您的XCode项目中从Reachability.swift
导入https://github.com/ashleymills/Reachability.swift/archive/master.zip文件
2.创建一个新的Swift类:ConnectionManager.swift
class ConnectionManager {
static let sharedInstance = ConnectionManager()
private var reachability : Reachability!
func observeReachability(){
self.reachability = Reachability()
NotificationCenter.default.addObserver(self, selector:#selector(self.reachabilityChanged), name: NSNotification.Name.reachabilityChanged, object: nil)
do {
try self.reachability.startNotifier()
}
catch(let error) {
print("Error occured while starting reachability notifications : \(error.localizedDescription)")
}
}
@objc func reachabilityChanged(note: Notification) {
let reachability = note.object as! Reachability
switch reachability.connection {
case .cellular:
print("Network available via Cellular Data.")
break
case .wifi:
print("Network available via WiFi.")
break
case .none:
print("Network is not available.")
break
}
}
}
3.在AppDelegate
文件中使用它:
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
ConnectionManager.sharedInstance.observeReachability()
return true
}
我没有用观察者回调来污染AppDelegate.swift
,而是建议只将观察者添加到相关的视图控制器中。
AppDelegate.swift
import ReachabilitySwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var reachability: Reachability?
func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? ) -> Bool
{
self.reachability = Reachability()
do
{
try reachability?.startNotifier()
}
catch
{
print( "ERROR: Could not start reachability notifier." )
}
return true
}
class func sharedAppDelegate() -> AppDelegate?
{
return UIApplication.shared.delegate as? AppDelegate
}
// Remaining functions
}
ViewController的示例:
class ExampleVC: UIViewController
{
override func viewDidLoad()
{
// Add reachability observer
if let reachability = AppDelegate.sharedAppDelegate()?.reachability
{
NotificationCenter.default.addObserver( self, selector: #selector( self.reachabilityChanged ),name: ReachabilityChangedNotification, object: reachability )
}
}
@objc private func reachabilityChanged( notification: NSNotification )
{
guard let reachability = notification.object as? Reachability else
{
return
}
if reachability.isReachable
{
if reachability.isReachableViaWiFi
{
print("Reachable via WiFi")
}
else
{
print("Reachable via Cellular")
}
}
else
{
print("Network not reachable")
}
}
}
针对swift 2.1和XCode 7进行了更新:
试试这个第三方高度评价的 Reachablity Class
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool
{
// Allocate a reachability object
self.reach = Reachability.reachabilityForInternetConnection()
// Tell the reachability that we DON'T want to be reachable on 3G/EDGE/CDMA
self.reach!.reachableOnWWAN = false
// Here we set up a NSNotification observer. The Reachability that caused the notification
// is passed in the object parameter
NSNotificationCenter.defaultCenter().addObserver(self,
selector: "reachabilityChanged:",
name: kReachabilityChangedNotification,
object: nil)
self.reach!.startNotifier()
return true
}
//Reachbality Notification Response
func reachabilityChanged(notification: NSNotification) {
if self.reach!.isReachableViaWiFi() || self.reach!.isReachableViaWWAN() {
print("Service avalaible!!!")
} else {
print("No service avalaible!!!")
AppHelper.showALertWithTag(0, title: constants.AppName.rawValue, message: "Please Check Your Internet Connection!", delegate: self, cancelButtonTitle: "OK", otherButtonTitle: nil)
}
}
更新了A. R. Younce对Swift 2的回答:
func checkForReachability(notification:NSNotification) {
if let networkReachability = notification.object as? Reachability {
let remoteHostStatus = networkReachability.currentReachabilityStatus()
if (remoteHostStatus == NotReachable) {
print("Not Reachable")
}
else if (remoteHostStatus == ReachableViaWiFi) {
print("Reachable via Wifi")
}
else {
print("Reachable")
}
} else {
print("Unknown")
}
}
基于this open source solution包裹上课
斯威夫特5
import Foundation
final class ReachabilityHandler {
private var reachability: Reachability? = Reachability()
// MARK: - LifeCycle
init() {
configure()
}
deinit {
NotificationCenter.default.removeObserver(self)
reachability?.stopNotifier()
}
// MARK: - Private
private func configure() {
NotificationCenter.default.addObserver(self,
selector: #selector(ReachabilityHandler.checkForReachability(notification:)),
name: Notification.Name.reachabilityChanged,
object: nil)
try? reachability?.startNotifier()
}
@objc private func checkForReachability(notification: NSNotification) {
let networkReachability = notification.object as? Reachability
if let remoteHostStatus = networkReachability?.connection {
switch remoteHostStatus {
case .none:
case .wifi,
.cellular:
}
}
}
}
在AppDelegate
class AppDelegate: UIResponder, UIApplicationDelegate {
private var rechabilityObserver: ReachabilityHandler?
var window: UIWindow?
// MARK: - LifeCycle
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
rechabilityObserver = ReachabilityHandler()
return true
}
}
Swift 2.0 - 使用可达性检查网络,NSNotification
AppDelegate.swift
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(self.checkNetworkStatus(_:)), name: "ReachabilityChangedNotification", object: nil);
do{self.reachability = try Reachability.reachabilityForInternetConnection()}catch{}
do{try self.reachability.startNotifier()}catch{}
self.checkNetworkStatus()
return true
}
声明networkStatus变量
var networkStatus : Reachability.NetworkStatus!
checkNetworkStatus()函数
func checkNetworkStatus()
{
networkStatus = reachability.currentReachabilityStatus
if (networkStatus == Reachability.NetworkStatus.NotReachable)
{
print("Not Reachable")
}
else
{
print("Reachable")
}
}
OtherClass.Swift
let delegate = UIApplication.sharedApplication().delegate as! AppDelegate
if (delegate.networkStatus!=Reachability.NetworkStatus.NotReachable)
{
// Call Webservice
}
else
{
delegate.checkNetworkStatus() //Not Reachable print
}
1)在项目中安装pod或添加ReachabilitySwift
2)在AppDelegate.swift中
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
NSNotificationCenter.defaultCenter().addObserver(self, selector:#selector(self.checkForReachability(_:)), name: "ReachabilityChangedNotification", object: nil);
do {
try self.reachability = Reachability.reachabilityForInternetConnection()
}
catch {
print(error)
}
do {
try self.reachability.startNotifier()
}
catch {
print(error)
}
return true
}
3)
func checkForReachability(notification:NSNotification) {
let networkReachability = notification.object as! Reachability;
let remoteHostStatus = networkReachability.currentReachabilityStatus
if (remoteHostStatus == .NotReachable) {
print("Not Reachable")
}
else if (remoteHostStatus == .ReachableViaWiFi || remoteHostStatus == .ReachableViaWWAN) {
print("Reachable via Wifi or via WWAN")
}
}