在我的应用程序中,我正在检查如果移动数据已关闭,则显示弹出窗口,例如检查您的数据连接。因为我写这个代码
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0)
if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false {
return false
}
let isReachable = flags == .Reachable
let needsConnection = flags == .ConnectionRequired
return isReachable && !needsConnection
}
}
但通过此代码,它唯一检查wifi是否连接。但如果我尝试使用3g移动数据,它总是向我显示您的移动数据未连接。那我怎么解决这个问题呢?
答案 0 :(得分:4)
尝试以下代码:
创建可达性类的对象,如
var internetReachability = Reachability()
现在在viewDidLoad(),
中写下以下代码 NSNotificationCenter.defaultCenter().addObserver(self, selector: "reachabilityChanged:", name: kReachabilityChangedNotification, object: nil)
self.internetReachability = Reachability.reachabilityForInternetConnection()
self.internetReachability.startNotifier()
self.updateInterfaceWithReachability(self.internetReachability)
现在创建函数来检查wifi和数据包的可达性,
func updateInterfaceWithReachability(reachability: Reachability)
{
let netStatus : NetworkStatus = reachability.currentReachabilityStatus()
switch (netStatus.rawValue)
{
case NotReachable.rawValue:
print("offline")
break
case ReachableViaWWAN.rawValue:
print("online")
break
case ReachableViaWiFi.rawValue:
print("online")
break
default :
print("offline")
break
}
}
// Rechability update status
func reachabilityChanged(sender : NSNotification!)
{
let curReach : Reachability = sender.object as! Reachability
self.updateInterfaceWithReachability(curReach)
}
希望这会对你有所帮助。
答案 1 :(得分:2)
如果您的应用程序中有任何超类,请使用以下代码
override func viewWillAppear(animated: Bool)
{
super.viewWillAppear(animated)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "ShowNetConnectivity", name: SHOW_NO_INTERNET_CONNECTION, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "DisssmissConnectivity", name: DISMISS_INTERNET_CONNECTION, object: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
print(flags.rawValue)
if (flags.rawValue == NotReachable.rawValue && flags.rawValue != ReachableViaWiFi.rawValue && flags.rawValue != ReachableViaWWAN.rawValue)
{
if(isConnectionAvailable == true)
{
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(SHOW_NO_INTERNET_CONNECTION, object: nil)
}
}else
{
if(isConnectionAvailable == false)
{
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(DISMISS_INTERNET_CONNECTION, object: nil)
}
}
}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)
}
override func viewWillDisappear(animated: Bool)
{
super.viewWillDisappear(animated)
NSNotificationCenter.defaultCenter().removeObserver(self, name: SHOW_NO_INTERNET_CONNECTION, object: nil)
NSNotificationCenter.defaultCenter().removeObserver(self, name: DISMISS_INTERNET_CONNECTION, object: nil)
}
答案 2 :(得分:2)
不需要“可到达性”窗格
Swift 4+和Xcode 11 +
import SystemConfiguration
protocol Utilities {}
extension NSObject: Utilities {
enum ReachabilityStatus {
case notReachable
case reachableViaWWAN
case reachableViaWiFi
}
var currentReachabilityStatus: ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size)
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return .notReachable
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .notReachable
}
if flags.contains(.reachable) == false {
// The target host is not reachable.
return .notReachable
}
else if flags.contains(.isWWAN) == true {
// WWAN connections are OK if the calling application is using the CFNetwork APIs.
return .reachableViaWWAN
}
else if flags.contains(.connectionRequired) == false {
// If the target host is reachable and no connection is required then we'll assume that you're on Wi-Fi...
return .reachableViaWiFi
}
else if (flags.contains(.connectionOnDemand) == true || flags.contains(.connectionOnTraffic) == true) && flags.contains(.interventionRequired) == false {
// The connection is on-demand (or on-traffic) if the calling application is using the CFSocketStream or higher APIs and no [user] intervention is needed
return .reachableViaWiFi
}
else {
return .notReachable
}
}
}
在任何方法中,请使用以下条件
if currentReachabilityStatus == .notReachable {
// Network Unavailable
} else {
// Network Available
}
答案 3 :(得分:1)
这是我怎么做的,它对我有用。 在我的viewDidLoad中:
do {
reachability = try Reachability.reachabilityForInternetConnection()
} catch {
print("Unable to create Reachability")
return
}
NSNotificationCenter.defaultCenter().addObserver(self,
selector: #selector(MainViewController.reachabilityChanged(_:)),
name: ReachabilityChangedNotification,
object: reachability)
do {
try reachability.startNotifier()
} catch {
print("This is not working.")
return
}
reachabilityChanged
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 {
showNoConnectionAlert()
print("Not reachable")
}
}
使用此Reachability
答案 4 :(得分:0)
我使用this pod repo不仅可以实现wifi或移动数据。您可以使用它做更多的事情,并且可以在ObjC或Swift中使用它。
最诚挚的问候。