我想知道是否有最好的方法来检测互联网连接发生的任何变化
我的意思是使用此代码
import SystemConfiguration
var isConnected: Bool = false
func isConnectedToNetwork()
{
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(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
self.isConnected = false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
if isReachable && !needsConnection
{
self.isConnected = true
}
else{
self.isConnected = false
}
}
它返回Internet连接的状态,但即使我需要在应用程序运行时继续检查Internet连接,所以我使用了此代码
NSTimer.scheduledTimerWithTimeInterval(10, target: self, selector: Selector("isConnectedToNetwork"), userInfo: nil, repeats: true)
每10秒检查一次互联网连接,但我相信有更好的方法。我的意思是使用观察者或其他东西。
比如这个
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardDidShow", name: UIKeyboardDidShowNotification, object: nil)
当键盘显示它检测到它并调用函数keyboardDidShow()
答案 0 :(得分:3)
Swift 3.0 +
这是我设法达到的最干净的解决方案。
您需要安装此广告连播https://github.com/AFNetworking/AFNetworking
然后import AFNetworking
声明NetworkReachability
类。
final class NetworkReachability {
private var previousStatus: AFNetworkReachabilityStatus = .unknown
/// Retrieves current network status once and stops monitoring reachability.
func getCurrentNetworkStatus(completion: ((AFNetworkReachabilityStatus) -> Void)?) {
previousStatus = .unknown
startMonitoring { currentStatus in
completion?(currentStatus)
self.stopMonitoring()
}
}
/// Monitors network reachability changes until reachable status is present. Then stops monitoring.
func getReachableNetworkStatus(completion: ((AFNetworkReachabilityStatus) -> Void)?) {
stopMonitoring()
startMonitoring { currentStatus in
completion?(currentStatus)
if currentStatus == .reachableViaWiFi || currentStatus == .reachableViaWWAN {
self.stopMonitoring()
}
}
}
/// Monitors network reachability changes, until stopMonitoring() is called.
func startMonitoring(newStatusCallback: ((AFNetworkReachabilityStatus) -> Void)?) {
AFNetworkReachabilityManager.shared().startMonitoring()
AFNetworkReachabilityManager.shared().setReachabilityStatusChange { currentStatus in
if currentStatus != .unknown && currentStatus != self.previousStatus {
newStatusCallback?(currentStatus)
}
self.previousStatus = currentStatus
}
}
func stopMonitoring() {
previousStatus = .unknown
AFNetworkReachabilityManager.shared().stopMonitoring()
}
}