SCNetworkReachabilitySetCallback error in Swift
I am trying to use the following code to set up a callback for SCNetworkReachability
// Create callback
let callback:(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> () = { (target: SCNetworkReachability!, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) in
// Do something
}
// Create UnsafeMutablePointer and initialise with callback
let p = UnsafeMutablePointer<(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> Void>.alloc(1)
p.initialize(callback)
// convert UnsafeMutablePointer to COpaquePointer
let cp = COpaquePointer(p)
// convert COppaquePointer to CFunctionPointer
let fp = CFunctionPointer<(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> Void>(cp)
if SCNetworkReachabilitySetCallback(reachability, fp, nil) != 0 {
println(SCError()) // SCError() is returning 0
}
The call SCNetworkReachabilitySetCallback
doesn't work - has anyone else had any success with this? Any idea where this might be wrong?
+3
source to share
2 answers
As of swift 1.2, you cannot pass functions written in swift using CFunctionPointer. It was mainly introduced for looping function pointers already defined in C to some other C (or ObjectC) routines.
One possible task would be to use objc_block in swift, for example:
let block: @objc_block (SCNetworkReachabilityRef, SCNetworkReachabilityFlags, UnsafePointer<Void>) -> Void = {
[weak self]
(reachability: SCNetworkReachabilityRef, flags: SCNetworkReachabilityFlags, data: UnsafePointer<Void>) in
// Do something e.g. check if network reachability has changed
if flags & SCNetworkReachabilityFlags(kSCNetworkReachabilityFlagsReachable) == 0 {
}
}
let blockObject = imp_implementationWithBlock(unsafeBitCast(block, AnyObject.self))
let fp = unsafeBitCast(blockObject, SCNetworkReachabilityCallBack.self)
// e.g. you can use 169.254.0.0 for local wifi connection
var reachability = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, ("169.254.0.0" as NSString).UTF8String).takeRetainedValue()
var context = SCNetworkReachabilityContext()
if SCNetworkReachabilitySetCallback(reachability!, fp, &context) == 1 {
if SCNetworkReachabilityScheduleWithRunLoop(reachability!, CFRunLoopGetCurrent(), NSDefaultRunLoopMode) == 0 {
println(SCError())
}
}
+1
source to share