2015-06-09 94 views
16

我正在嘗試檢查用戶是否具有Internet連接,並且該過程的一部分涉及調用withUnsafePointer。在斯威夫特1.x中,我可以使用:withUnsafePointer in Swift 2

var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) 
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) 
zeroAddress.sin_family = sa_family_t(AF_INET) 

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

但是現在有了斯威夫特2,我得到一個錯誤說

不能援引「withUnsafePointer」類型的參數列表「 (INOUT SOCKADDR_IN,(_) - > _)」

我看着Xcode的使用,這就是:

enter image description here

所以我試圖用

withUnsafePointer(&zeroAddress) {(pointer: UnsafePointer<sockaddr_in>) -> sockaddr_in in 
    SCNetworkReachabilityCreateWithAddress(nil, pointer).takeRetainedValue() 
} 

以及

withUnsafePointer(&zeroAddress) {(pointer: UnsafePointer<sockaddr_in>) -> AnyObject in 
    SCNetworkReachabilityCreateWithAddress(nil, pointer).takeRetainedValue() 
} 

,他們都給予cannot invoke...編譯時錯誤。在Swift 2.x中使用withUnsafePointer的正確方法是什麼?

回答

23

錯誤消息是誤導性的,問題是, SCNetworkReachabilityCreateWithAddress()不會再返回 非託管對象,所以你不能調用 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)) 
} 

注也喜歡struct sockaddr_in簡化創建C結構的這是Swift 1.2引入的 (如果我沒記錯的話)。

+4

所以現在好多了.. – Berik

1

斯威夫特3:

var zeroAddress = sockaddr_in() 
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) 
zeroAddress.sin_family = sa_family_t(AF_INET) 

let defaultRouteReachability = withUnsafePointer(to: &zeroAddress, { 
    _ = $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in 
     SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) 
    } 
}) 
+0

喜廖氏...該行 - > SCNetworkReachabilityCreateWithAddress(零,zeroSockAddress)我得到出現以下錯誤.-->使用未解決的標識符'SCNetworkReachabilityCreateWithAddress' –

0

Swift3使用

  var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0)) 
     zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress)) 
     zeroAddress.sin_family = sa_family_t(AF_INET) 

     let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) { 
      $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in 
       SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress) 
      } 
     } 

     var flags: SCNetworkReachabilityFlags = SCNetworkReachabilityFlags(rawValue: 0) 
     if SCNetworkReachabilityGetFlags(defaultRouteReachability!, &flags) == false { 
      return false 
     }