Created
February 27, 2016 00:34
-
-
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.
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
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
seems it break on mac 10.15:(