Created
September 7, 2014 17:31
-
-
Save regnerjr/f915e2510e1e079e597a to your computer and use it in GitHub Desktop.
Handling Notifications in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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