Skip to content

Instantly share code, notes, and snippets.

@ftiff
Created March 30, 2016 14:42
Show Gist options
  • Save ftiff/f482fd1280cb6a5ca77a55b08b332396 to your computer and use it in GitHub Desktop.
Save ftiff/f482fd1280cb6a5ca77a55b08b332396 to your computer and use it in GitHub Desktop.
OS X / Swift: Trigger function when network configuration changes
/**
* Network Change Notifier
*
* Made by François 'ftiff' Levaux-Tiffreau - [email protected]
*
*
* Simply modify "changed"
*
*/
import Cocoa
import SystemConfiguration
let changed: SCDynamicStoreCallBack = {dynamicStore,_,_ in
print("Network configuration changed")
}
var dynamicContext = SCDynamicStoreContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let dcAddress = withUnsafeMutablePointer(&dynamicContext, {UnsafeMutablePointer<SCDynamicStoreContext>($0)})
if let dynamicStore = SCDynamicStoreCreate(kCFAllocatorDefault, "io.fti.networkconfigurationchanged", changed, dcAddress){
let keys: [CFStringRef] = ["State:/Network/Global/IPv4"]
let keyPointer = UnsafeMutablePointer<UnsafePointer<Void>>(keys)
let keysArray = CFArrayCreate(nil, keyPointer, 1, nil)
SCDynamicStoreSetNotificationKeys(dynamicStore, nil, keysArray)
let loop = SCDynamicStoreCreateRunLoopSource(kCFAllocatorDefault, dynamicStore, 0)
CFRunLoopAddSource(CFRunLoopGetCurrent(), loop, kCFRunLoopDefaultMode)
CFRunLoopRun()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment