Skip to content

Instantly share code, notes, and snippets.

@rickw
Last active August 29, 2015 14:14
Show Gist options
  • Save rickw/29976f0cacec2eaefa35 to your computer and use it in GitHub Desktop.
Save rickw/29976f0cacec2eaefa35 to your computer and use it in GitHub Desktop.
Reachability Callback Setup
import Foundation
import SystemConfiguration
var reach:SCNetworkReachability!
reach = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "apple.com").takeRetainedValue()
typealias ChangeBlock = (UInt32) -> ()
let block:ChangeBlock = {status in
// swift compleation block
}
let blockPtr = UnsafeMutablePointer<ChangeBlock>.alloc(1)
blockPtr.initialize(block)
let blockVoidPtr = UnsafeMutablePointer<Void>(blockPtr)
// Create callback
let callback:(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> () = { (target, flags, info) in
let ptr = UnsafeMutablePointer<ChangeBlock>(info)
let block:ChangeBlock = ptr.memory
block(flags)
}
// Create UnsafeMutablePointer and initialise with callback
let callbackPtr = UnsafeMutablePointer<(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> Void>.alloc(1)
callbackPtr.initialize(callback)
// convert UnsafeMutablePointer to COpaquePointer
let cop = COpaquePointer(callbackPtr)
// convert COppaquePointer to CFunctionPointer
let cfptr = CFunctionPointer<(SCNetworkReachability!, SCNetworkReachabilityFlags, UnsafeMutablePointer<Void>) -> Void>(cop)
let context = SCNetworkReachabilityContext(version: 0, info: blockVoidPtr, retain: nil, release: nil, copyDescription: nil)
let contextPtr = UnsafeMutablePointer<SCNetworkReachabilityContext>.alloc(1)
contextPtr.initialize(context)
SCNetworkReachabilitySetCallback(reach, cfptr, contextPtr)
let que = dispatch_queue_create("me.swiftti.reachability", nil)
SCNetworkReachabilitySetDispatchQueue(reach, que)
// on deinit() do
contextPtr.destroy()
contextPtr.dealloc(1)
callbackPtr.destroy()
callbackPtr.dealloc(1)
blockVoidPtr.destroy()
blockVoidPtr.dealloc(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment