Check for internet connection with Swift

前端 未结 21 1831
别跟我提以往
别跟我提以往 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: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.

提交回复
热议问题