您的第一个问题可以用解决
let reachability = host.withCString { SCNetworkReachabilityCreateWithName(nil, $0).takeRetainedValue()}在闭包内部,
$0是一个指向NUL终止的String的UTF-8表示形式的指针。
更新: 正如Nate Cook在现在删除的答案中以及在这里所说的那样,您实际上可以将Swift字符串传递给
UnsafePointer<UInt8>直接采用以下形式的函数:
let reachability = SCNetworkReachabilityCreateWithName(nil, host).takeRetainedValue()
不幸的是(据我所知)目前还没有解决您的第二个问题的方法。
SCNetworkReachabilitySetCallback需要将指向C函数的指针作为第二个参数,并且目前没有方法可以传递Swift函数或闭包。请注意,该文档
SCNetworkReachabilityCallBack
仅显示了Objective-C,而没有显示Swift。
Swift 2的更新: 现在可以将Swift闭包传递给带有函数指针参数的C函数。也
SCNetworkReachabilityCreateWithName()不再返回非托管对象:
let host = "google.com"var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)let reachability = SCNetworkReachabilityCreateWithName(nil, host)!SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in print(flags)}, &context)SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), kCFRunLoopCommonModes)Swift 3(Xpre 8)更新:
let host = "google.com"var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)let reachability = SCNetworkReachabilityCreateWithName(nil, host)!SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in print(flags) }, &context)SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)


