当我试着在我的iPhone上检查网络连接时,我得到了一堆错误。有人能帮我解决这个问题吗?
代码:
import Foundation
import SystemConfiguration
public class Reachability {
class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
}
代码的错误:
如果它是不可读的,错误1说:
'Int'不能转换为'SCNetworkReachabilityFlags'
错误2和3:
找不到一个超载的'init'接受提供的参数
从iOS 12开始,NWPathMonitor取代了Reachability。用这个:
import Network
struct Internet {
private static let monitor = NWPathMonitor()
static var active = false
static var expensive = false
/// Monitors internet connectivity changes. Updates with every change in connectivity.
/// Updates variables for availability and if it's expensive (cellular).
static func start() {
guard monitor.pathUpdateHandler == nil else { return }
monitor.pathUpdateHandler = { update in
Internet.active = update.status == .satisfied ? true : false
Internet.expensive = update.isExpensive ? true : false
}
monitor.start(queue: DispatchQueue(label: "InternetMonitor"))
}
}
在使用:
Internet.start()
if Internet.active {
// do something
}
if Internet.expensive {
// device is using Cellular data or WiFi hotspot
}
Swift 5.5, iOS 12+,没有更多的第三方库。
请检查这个要点https://gist.github.com/dimohamdy/5166ba6c88f6954fa6b23bc9f28cbe12
使用
startNetworkReachabilityObserver()
if Reachability.shared.isConnected {
print("no internet connection")
}
Code
import Network
import Foundation
class Reachability {
static var shared = Reachability()
lazy private var monitor = NWPathMonitor()
var isConnected: Bool {
return monitor.currentPath.status == .satisfied
}
func startNetworkReachabilityObserver() {
monitor.pathUpdateHandler = { path in
if path.status == .satisfied {
NotificationCenter.default.post(name: Notifications.Reachability.connected.name, object: nil)
} else if path.status == .unsatisfied {
NotificationCenter.default.post(name: Notifications.Reachability.notConnected.name, object: nil)
}
}
let queue = DispatchQueue.global(qos: .background)
monitor.start(queue: queue)
}
}
这些答案中有许多已经不再适用。
原因是使用vpn(因为冠状病毒,我们现在通过vpn而不是公司的wifi进行测试)
使用苹果的网络框架,并基于这里的代码https://medium.com/@udaykiran.munaga/swift-check-for-internet-connectivity-14e355fa10c5,我能够分别检测到wifi和蜂窝网络。由于使用vpn,路径通常保持满意,因此isConnectedToNetwork()总是返回true。
下面的代码使用了apple Network框架,但重新编写,以便在现有代码中仍然使用Reachability.isConnectedToNetwork()。
import Network
class Reachability {
static let shared = Reachability()
let monitorForWifi = NWPathMonitor(requiredInterfaceType: .wifi)
let monitorForCellular = NWPathMonitor(requiredInterfaceType: .cellular)
private var wifiStatus: NWPath.Status = .requiresConnection
private var cellularStatus: NWPath.Status = .requiresConnection
var isReachable: Bool { wifiStatus == .satisfied || isReachableOnCellular }
var isReachableOnCellular: Bool { cellularStatus == .satisfied }
func startMonitoring() {
monitorForWifi.pathUpdateHandler = { [weak self] path in
self?.wifiStatus = path.status
if path.status == .satisfied {
DLog.message("Wifi is connected!")
// post connected notification
} else {
DLog.message("No wifi connection.")
// post disconnected notification
}
}
monitorForCellular.pathUpdateHandler = { [weak self] path in
self?.cellularStatus = path.status
if path.status == .satisfied {
DLog.message("Cellular connection is connected!")
// post connected notification
} else {
DLog.message("No cellular connection.")
// post disconnected notification
}
}
let queue = DispatchQueue(label: "NetworkMonitor")
monitorForCellular.start(queue: queue)
monitorForWifi.start(queue: queue)
}
func stopMonitoring() {
monitorForWifi.cancel()
monitorForCellular.cancel()
}
class func isConnectedToNetwork() -> Bool {
return shared.isReachable
}
}
然后在你的Appdelegate中didFinishLaunchingWithOptions: start monitoring。
Reachability.shared.startMonitoring()
更新版本的@martin的答案Swift 5+使用组合。它还包括iOS 14的不可用原因检查。
import Combine
import Network
enum NetworkType {
case wifi
case cellular
case loopBack
case wired
case other
}
final class ReachabilityService: ObservableObject {
@Published var reachabilityInfos: NWPath?
@Published var isNetworkAvailable: Bool?
@Published var typeOfCurrentConnection: NetworkType?
private let monitor = NWPathMonitor()
private let backgroundQueue = DispatchQueue.global(qos: .background)
init() {
setUp()
}
init(with interFaceType: NWInterface.InterfaceType) {
setUp()
}
deinit {
monitor.cancel()
}
}
private extension ReachabilityService {
func setUp() {
monitor.pathUpdateHandler = { [weak self] path in
self?.reachabilityInfos = path
switch path.status {
case .satisfied:
print("ReachabilityService: satisfied")
self?.isNetworkAvailable = true
break
case .unsatisfied:
print("ReachabilityService: unsatisfied")
if #available(iOS 14.2, *) {
switch path.unsatisfiedReason {
case .notAvailable:
print("ReachabilityService: unsatisfiedReason: notAvailable")
break
case .cellularDenied:
print("ReachabilityService: unsatisfiedReason: cellularDenied")
break
case .wifiDenied:
print("ReachabilityService: unsatisfiedReason: wifiDenied")
break
case .localNetworkDenied:
print("ReachabilityService: unsatisfiedReason: localNetworkDenied")
break
@unknown default:
print("ReachabilityService: unsatisfiedReason: default")
}
} else {
// Fallback on earlier versions
}
self?.isNetworkAvailable = false
break
case .requiresConnection:
print("ReachabilityService: requiresConnection")
self?.isNetworkAvailable = false
break
@unknown default:
print("ReachabilityService: default")
self?.isNetworkAvailable = false
}
if path.usesInterfaceType(.wifi) {
self?.typeOfCurrentConnection = .wifi
} else if path.usesInterfaceType(.cellular) {
self?.typeOfCurrentConnection = .cellular
} else if path.usesInterfaceType(.loopback) {
self?.typeOfCurrentConnection = .loopBack
} else if path.usesInterfaceType(.wiredEthernet) {
self?.typeOfCurrentConnection = .wired
} else if path.usesInterfaceType(.other) {
self?.typeOfCurrentConnection = .other
}
}
monitor.start(queue: backgroundQueue)
}
}
用法:
在视图模型中:
private let reachability = ReachabilityService()
init() {
reachability.$isNetworkAvailable.sink { [weak self] isConnected in
self?.isConnected = isConnected ?? false
}.store(in: &cancelBag)
}
在你的控制器中:
viewModel.$isConnected.sink { [weak self] isConnected in
print("isConnected: \(isConnected)")
DispatchQueue.main.async {
//Update your UI in here
}
}.store(in: &bindings)
iOS12 Swift 4和Swift 5
如果你只是想检查连接,你的最低目标是iOS12,那么你可以使用NWPathMonitor
import Network
它需要一些属性的设置。
let internetMonitor = NWPathMonitor()
let internetQueue = DispatchQueue(label: "InternetMonitor")
private var hasConnectionPath = false
我创建了一个函数来启动它。你可以在viewdidload或其他地方做这个。我派了个保镖,你想怎么打就怎么打。
func startInternetTracking() {
// only fires once
guard internetMonitor.pathUpdateHandler == nil else {
return
}
internetMonitor.pathUpdateHandler = { update in
if update.status == .satisfied {
print("Internet connection on.")
self.hasConnectionPath = true
} else {
print("no internet connection.")
self.hasConnectionPath = false
}
}
internetMonitor.start(queue: internetQueue)
}
/// will tell you if the device has an Internet connection
/// - Returns: true if there is some kind of connection
func hasInternet() -> Bool {
return hasConnectionPath
}
现在只需调用helper函数hasInternet()来查看是否有。它实时更新。请参阅Apple文档中的NWPathMonitor。它有更多的功能,如取消(),如果你需要停止跟踪连接,你正在寻找的互联网类型等。
https://developer.apple.com/documentation/network/nwpathmonitor