Skip to content

Instantly share code, notes, and snippets.

@regnerjr
Created September 7, 2014 17:31
Show Gist options
  • Save regnerjr/f915e2510e1e079e597a to your computer and use it in GitHub Desktop.
Save regnerjr/f915e2510e1e079e597a to your computer and use it in GitHub Desktop.
Handling Notifications in Swift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow!
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
let dev = UIDevice.currentDevice()
dev.beginGeneratingDeviceOrientationNotifications()
//Handled by selector
let nc = NSNotificationCenter.defaultCenter()
nc.addObserver(self, selector: "orientationChanged:", name: UIDeviceOrientationDidChangeNotification, object: dev)
//using an inline closure
nc.addObserverForName(UIDeviceOrientationDidChangeNotification, object: dev, queue: NSOperationQueue.mainQueue(), usingBlock: {
note in if let object: UIDevice = note.object? as? UIDevice {
println("orientationChangedInlineBlock: \(object.orientation.toRaw())")
}})
//using a named closure
nc.addObserverForName(UIDeviceOrientationDidChangeNotification, object: dev, queue: NSOperationQueue.currentQueue(), usingBlock: orientationBlock)
window.backgroundColor = UIColor.whiteColor()
window.makeKeyAndVisible()
return true
}
let orientationBlock = { (note: NSNotification!) -> () in
if let deviceNotification = note.object? as? UIDevice {
println("orientationBlock \(deviceNotification.orientation.toRaw())")
}
}
func orientationChanged(note: NSNotification) -> () {
if let object: UIDevice = note.object? as? UIDevice {
println("orientationChanged: \(object.orientation.toRaw())")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment