Skip to content

Instantly share code, notes, and snippets.

Created February 27, 2016 00:34
Show Gist options
  • Save rsattar/ed74982428003db8e875 to your computer and use it in GitHub Desktop.
Save rsattar/ed74982428003db8e875 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 ""
} 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 {
class_getInstanceMethod(aClass, "bundleIdentifier"),
class_getInstanceMethod(aClass, "fakeBundleIdentifier")
return true
return false
// 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
presentNotification("Hi there! \(NSDate().timeIntervalSince1970)")
Copy link

SLboat commented Oct 8, 2019

seems it break on mac 10.15:(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment