Check for internet connection with Swift

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

    Use this for Swift-5+

    import Foundation
    import UIKit
    import SystemConfiguration
    
    public class InternetConnectionManager {
    
    
        private init() {
    
        }
    
        public static func isConnectedToNetwork() -> Bool {
    
            var zeroAddress = sockaddr_in()
            zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
            zeroAddress.sin_family = sa_family_t(AF_INET)
            guard let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, {
    
                $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
    
                    SCNetworkReachabilityCreateWithAddress(nil, $0)
    
                }
    
            }) else {
    
                return false
            }
            var flags = SCNetworkReachabilityFlags()
            if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
                return false
            }
            let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
            let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
            return (isReachable && !needsConnection)
        }
    
    }
    

    Usage:

    InternetConnectionManager.isConnectedToNetwork{
        print("Connected")
    }else{
        print("Not Connected")
    }
    

    Or Just use this framework for more Utilities: Link

提交回复
热议问题