withUnsafePointer in Swift 2

后端 未结 3 1155
挽巷
挽巷 2020-12-28 17:41

I\'m trying to check if the user has internet connection, and part of the process involves invoking withUnsafePointer. In Swift 1.x, I was able to use:

3条回答
  •  无人及你
    2020-12-28 18:25

    The error message is misleading, the problem is that SCNetworkReachabilityCreateWithAddress() does not return an unmanaged object anymore, so you must not call takeRetainedValue():

    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))
    }
    

    Note also the simplified creation of C structs like struct sockaddr_in which was introduced with Swift 1.2 (if I remember correctly).

提交回复
热议问题