Check for internet connection with Swift

前端 未结 21 1560
别跟我提以往
别跟我提以往 2020-11-22 05:59

When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this?

The code:

import Foundation
impo         


        
21条回答
  •  难免孤独
    2020-11-22 06:09

    here my solution for swift 2.3 with the lib (Reachability.swift)

    Go into your Podfile and add :

    pod 'ReachabilitySwift', '~> 2.4' // swift 2.3
    

    Then into your terminal :

    pod install
    

    Then create a new file ReachabilityManager and add code below :

    import Foundation
    import ReachabilitySwift
    
    enum ReachabilityManagerType {
        case Wifi
        case Cellular
        case None
    }
    
    class ReachabilityManager {
        static let sharedInstance = ReachabilityManager()
    
        private var reachability: Reachability!
        private var reachabilityManagerType: ReachabilityManagerType = .None
    
    
        private init() {
            do {
                self.reachability = try Reachability.reachabilityForInternetConnection()
            } catch {
                print("Unable to create Reachability")
                return
            }
    
            NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ReachabilityManager.reachabilityChanged(_:)),name: ReachabilityChangedNotification,object: self.reachability)
            do{
                try self.reachability.startNotifier()
            }catch{
                print("could not start reachability notifier")
            }
        }
    
        @objc private func reachabilityChanged(note: NSNotification) {
    
            let reachability = note.object as! Reachability
    
            if reachability.isReachable() {
                if reachability.isReachableViaWiFi() {
                    self.reachabilityManagerType = .Wifi
                } else {
                    self.reachabilityManagerType = .Cellular
                }
            } else {
                self.reachabilityManagerType = .None
            }
        }
    }
    
    extension ReachabilityManager {
    
        func isConnectedToNetwork() -> Bool {
            return reachabilityManagerType != .None
        }
    
    }
    

    How use it:

    go into your AppDelegate.swift and add the code below :

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
         ReachabilityManager.sharedInstance
    }
    

    Then when you want to check if the device is connected to internet do :

    if ReachabilityManager.sharedInstance.isConnectedToNetwork() {
       // Connected
    } else {
      // Not connected
    }
    

提交回复
热议问题