Swift 3 通过可达性检查互联网连接

Posted

技术标签:

【中文标题】Swift 3 通过可达性检查互联网连接【英文标题】:Swift 3 check internet connection with Reachability 【发布时间】:2016-12-27 22:56:21 【问题描述】:

所以我正在考虑使用这个 GitHub api 来检查主机的可达性。:https://github.com/ashleymills/Reachability.swift/tree/feature/ios10

但是它非常简单,我在尝试编写将使用此代码的函数时遇到了一些错误。我从 viewdidload 调用它

setupReachability(hostName: nil)

var reachability:Reachability?

var connected = false

func setupReachability (hostName:String?) 
    do 
        let reachability = try hostName == nil ? Reachability() : Reachability(hostname: hostName!)
        self.reachability = reachability

        try! self.reachability?.startNotifier()
     catch ReachabilityError.FailedToCreateWithAddress(let address) 
        print(address)
        return
     catch 
    //now that the reacability function is created set a notification
    NotificationCenter.default.addObserver(self, selector: "reachabilityChanged", name: ReachabilityChangedNotification, object: reachability)



func reachabilityChanged(notification: Notification) 
    let reachability = notification.object as! Reachability

    if reachability.isReachable 
        if reachability.isReachableViaWiFi 
            connected = true
            print("Connected via WiFi")
         else 
            connected = true
            print("Connected via Cellular")
        
     else 
        connected = false
        print("Not Connected")
    

这是我的错误日志:

2016-12-28 08:53:25.441 ParseStarterProject-Swift[92944:1919466] Simulator user has requested new graphics quality: 100
2016-12-28 08:53:29.697 ParseStarterProject-Swift[92944:1919546] -[ParseStarterProject_Swift.PackViewController reachabilityChanged]: unrecognized selector sent to instance 0x7fafabd0bb40
2016-12-28 08:53:29.712 ParseStarterProject-Swift[92944:1919546] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[ParseStarterProject_Swift.PackViewController reachabilityChanged]: unrecognized selector sent to instance 0x7fafabd0bb40'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000010ad98d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x000000010a7fa21e objc_exception_throw + 48
    2   CoreFoundation                      0x000000010ae08f04 -[NSObject(NSObject) doesNotRecognizeSelector:] + 132
    3   CoreFoundation                      0x000000010ad1e005 ___forwarding___ + 1013
    4   CoreFoundation                      0x000000010ad1db88 _CF_forwarding_prep_0 + 120
    5   CoreFoundation                      0x000000010ad365ec __CFNOTIFICATIONCENTER_IS_CALLING_OUT_TO_AN_OBSERVER__ + 12
    6   CoreFoundation                      0x000000010ad364eb _CFXRegistrationPost + 427
    7   CoreFoundation                      0x000000010ad36252 ___CFXNotificationPost_block_invoke + 50
    8   CoreFoundation                      0x000000010acf9282 -[_CFXNotificationRegistrar find:object:observer:enumerator:] + 2018
    9   CoreFoundation                      0x000000010acf831b _CFXNotificationPost + 667
    10  Foundation                          0x000000010a2c081b -[NSNotificationCenter postNotificationName:object:userInfo:] + 66
    11  ParseStarterProject-Swift           0x000000010983fabe _TFC25ParseStarterProject_Swift12ReachabilityP33_3EC4A4DB94B171724E68742C2AA9888E19reachabilityChangedfT_T_ + 462
    12  ParseStarterProject-Swift           0x0000000109841205 _TFFC25ParseStarterProject_Swift12Reachability13startNotifierFzT_T_U_FT_T_ + 21
    13  ParseStarterProject-Swift           0x0000000109811f17 _TTRXFo___XFdCb___ + 39
    14  libdispatch.dylib                   0x000000010df1b978 _dispatch_call_block_and_release + 12
    15  libdispatch.dylib                   0x000000010df450cd _dispatch_client_callout + 8
    16  libdispatch.dylib                   0x000000010df22e17 _dispatch_queue_serial_drain + 236
    17  libdispatch.dylib                   0x000000010df23b4b _dispatch_queue_invoke + 1073
    18  libdispatch.dylib                   0x000000010df2402b _dispatch_queue_override_invoke + 683
    19  libdispatch.dylib                   0x000000010df26385 _dispatch_root_queue_drain + 720
    20  libdispatch.dylib                   0x000000010df26059 _dispatch_worker_thread3 + 123
    21  libsystem_pthread.dylib             0x000000010e39f712 _pthread_wqthread + 1299
    22  libsystem_pthread.dylib             0x000000010e39f1ed start_wqthread + 13
)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb) 

编辑

【问题讨论】:

在尝试使用其他第三方之前,您是否尝试过 Apple 流行的可达性示例? pod 'AppleReachability' 【参考方案1】:

您忘记了 reachabilityChanged: 选择器上的冒号。您需要它来指示要传递的参数:

NotificationCenter.default.addObserver(self, selector: "reachabilityChanged:", name: ReachabilityChangedNotification, object: reachability)

【讨论】:

我已经编辑了我的问题。它克服了那个错误,现在它提示输入钥匙串并崩溃

以上是关于Swift 3 通过可达性检查互联网连接的主要内容,如果未能解决你的问题,请参考以下文章

Swift 中的 AFNetworking 可达性管理器

Swift 4 中的可达性问题

如何在 Swift 3 或 Swift 4 中检查互联网连接? [复制]

Swift:执行 Segue 不触发 - 无错误(可达性)

我应该啥时候检查互联网连接

使用 Reachability 2.2 检查 Internet 连接