Skip to content

Instantly share code, notes, and snippets.

@code4you2021
Created November 8, 2021 02:18
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save code4you2021/cf184702b298181238aeb3fd781db203 to your computer and use it in GitHub Desktop.
Save code4you2021/cf184702b298181238aeb3fd781db203 to your computer and use it in GitHub Desktop.
Deliver an OSX notification with Swift
// Remember: import UserNotifications
func sendNotification(title: String, body: String = "") {
let content = UNMutableNotificationContent()
content.title = title
if body.count > 0 {
content.body = body
}
// you can alse add a subtitle
content.subtitle = "subtitle here... "
let uuidString = UUID().uuidString
let request = UNNotificationRequest(
identifier: uuidString,
content: content, trigger: nil)
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.requestAuthorization(options: [.alert, .sound]) { _, _ in }
notificationCenter.add(request)
}
/*
* How to use
* sendNotification(title: "Hello", body: "I am a programmer")
*/
@JodhwaniMadhur
Copy link

JodhwaniMadhur commented Dec 28, 2021

Line 19 of UNUserNotificationCenter gives an error like this one =>

*** First throw call stack:
(
	0   CoreFoundation                      0x00007ff8011cae5b __exceptionPreprocess + 242
	1   libobjc.A.dylib                     0x00007ff800f2bb9d objc_exception_throw + 48
	2   Foundation                          0x00007ff802081653 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 267
	3   UserNotifications                   0x00007ff80bcefac0 __53+[UNUserNotificationCenter currentNotificationCenter]_block_invoke + 1041
	4   libdispatch.dylib                   0x000000010059c874 _dispatch_client_callout + 8
	5   libdispatch.dylib                   0x000000010059e038 _dispatch_once_callout + 87
	6   UserNotifications                   0x00007ff80bcef6ad +[UNUserNotificationCenter currentNotificationCenter] + 101
	7   UNNotificationCenter                0x0000000100002c45 $s20UNNotificationCenter16sendNotification5title4bodyySS_SStF + 837
	8   UNNotificationCenter                0x00000001000028b8 main + 88
	9   dyld                                0x000000010001d4fe start + 462
)
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bundleProxyForCurrentProcess is nil: mainBundle.bundleURL file:'XYZ'
terminating with uncaught exception of type NSException

Any idea as to how I should solve this, I am trying to use your code from C++ using a bridging header and call it with different titles and subtitles and stuff but I don't know how to do it with this error.

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