检查互联网连接在Swift 2(iOS 9)

前端之家收集整理的这篇文章主要介绍了检查互联网连接在Swift 2(iOS 9)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
当我试图通过在XCode中使用Swift 2检查我的iPhone上的互联网连接,我得到一堆错误。任何人都可以帮助我解决这个问题?

代码

import Foundation
import SystemConfiguration

public class Reachability {

class func isConnectedToNetwork() -> Bool {

    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)

    let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
        SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0))
    }

    var flags: SCNetworkReachabilityFlags = 0

    if SCNetworkReachabilityGetFlags(defaultRouteReachability,&flags) == 0 {
        return false
    }

    let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionrequired)) != 0

    return (isReachable && !needsConnection) ? true : false
}

}

代码错误

如果它不可读,错误1说:

‘Int’ is not convertible to ‘SCNetworkReachabilityFlags’

错误2& 3:

Could not find an overload for ‘init’ that accepts the supplied arguments

Xcode 7.0
import SystemConfiguration

public class Reachability {
    class func isConnectedToNetwork() -> Bool {
        var zeroAddress = sockaddr_in()
        zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
        zeroAddress.sin_family = sa_family_t(AF_INET)
        let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
            SCNetworkReachabilityCreateWithAddress(nil,UnsafePointer($0))
        }
        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)
    }
}
原文链接:https://www.f2er.com/swift/321759.html

猜你在找的Swift相关文章