Check for internet connection with Swift

前端 未结 21 1528
别跟我提以往
别跟我提以往 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:27
    struct Connectivity {
            static let sharedInstance = NetworkReachabilityManager()!
            static var isConnectedToInternet:Bool {
                return self.sharedInstance.isReachable
            }
        }
    

    Now call it

    if Connectivity.isConnectedToInternet{
                call_your_methods_here()
            }else{
                show_alert_for_noInternet()
            }
    
    0 讨论(0)
  • 2020-11-22 06:28

    While it may not directly determine whether the phone is connected to a network, the simplest(, cleanest?) solution would be to 'ping' Google, or some other server, (which isn't possible unless the phone is connected to a network):

    private var urlSession:URLSession = {
        var newConfiguration:URLSessionConfiguration = .default
        newConfiguration.waitsForConnectivity = false
        newConfiguration.allowsCellularAccess = true
        return URLSession(configuration: newConfiguration)
    }()
    
    public func canReachGoogle() -> Bool
    {
        let url = URL(string: "https://8.8.8.8")
        let semaphore = DispatchSemaphore(value: 0)
        var success = false
        let task = urlSession.dataTask(with: url!)
        { data, response, error in
            if error != nil
            {
                success = false
            }
            else
            {
                success = true
            }
            semaphore.signal()
        }
    
        task.resume()
        semaphore.wait()
    
        return success
    }
    

    If you're concerned that the server may be down or may block your IP, you can always ping multiple servers in a similar fashion and return whether any of them are reachable. Or have someone set up a dedicated server just for this purpose.

    0 讨论(0)
  • 2020-11-22 06:29

    Although it does not directly answers your question, I would like to mention Apple recentely had this talk:

    https://developer.apple.com/videos/play/wwdc2018/714/

    At around 09:55 he talks about doing this stuff you are asking about:

    1. Check connection
    2. If connection -> Do something
    3. If no connection -> Do something else (wait? retry?)

    However, this has a few pitfalls:

    • What if in step 2 it says it has a connection, but 0.5 seconds later he hasn't?
    • What if the user is behind a proxy
    • Last but not least, what if some answers here can not determine the connectivity right? (I am sure that if you rapidly switch your connection, go to wi-fi and turn it off (just make it complicated), it almost never can correctly determine whetever I got a connection or not).
    • Quote from the video: "There is no way to guarentee whether a future operation will succeed or not"

    The following points are some best practices according to Apple:

    • set waitsForConnectivity to true (https://developer.apple.com/documentation/foundation/urlsessionconfiguration/2908812-waitsforconnectivity)
    • respond to the delegate method taskIsWaitingForConnectivity (https://developer.apple.com/documentation/foundation/urlsessiontaskdelegate/2908819-urlsession). This is Apple's recommended way to check for connectivity, as mentioned in the video at 33:25.

    According to the talk, there shouldn't be any reason to pre-check whetever you got internet connection or not, since it may not be accurate at the time you send your request to the server.

    0 讨论(0)
提交回复
热议问题