Skip to content

Instantly share code, notes, and snippets.

@rsattar
Created February 27, 2016 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsattar/da0061130015485ba7a7 to your computer and use it in GitHub Desktop.
Save rsattar/da0061130015485ba7a7 to your computer and use it in GitHub Desktop.
Swift script that shows how to deliver notifications to OS X Notification Center using purely CLI. This can be pasted into a Playground and executed, too.
import Foundation
// Create a method that will be called instead of
// "bundleIdentifier()" that returns a non-empty
// bundle id, even for a CLI script
extension NSBundle {
func fakeBundleIdentifier() -> NSString {
if self == NSBundle.mainBundle() {
return "dont.mind.me.totally.a.normal.bundleid"
} else {
return self.fakeBundleIdentifier()
}
}
}
// Method to dynamically swizzle the "bundleIdentifier()" method
// which the system will call on the main bundle with ours that
// returns a non-empty value
func swizzleToReturnANonEmptyBundleIdentifier() -> Bool {
if let aClass = objc_getClass("NSBundle") as? AnyClass {
method_exchangeImplementations(
class_getInstanceMethod(aClass, "bundleIdentifier"),
class_getInstanceMethod(aClass, "fakeBundleIdentifier")
)
return true
}
return false
}
swizzleToReturnANonEmptyBundleIdentifier()
//////////////////////////////////////////////////////////////////
// Now, the actual usage of notifications becomes very simple :)
func presentNotification(message: String) {
let notification = NSUserNotification()
notification.identifier = "\(NSDate().timeIntervalSince1970)"
notification.title = "Title"
notification.subtitle = "Subtitle"
notification.informativeText = message
NSUserNotificationCenter.defaultUserNotificationCenter().deliverNotification(notification)
}
presentNotification("Hi there! \(NSDate().timeIntervalSince1970)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment