1

我正在尝试从独立的 Objective-C 文件中抛出通知。该NSUserNotificationAPI 将在 OSX 11 之后被弃用,所以我希望切换到更新的UNUserNotification界面。

不幸的是,我无法从谷歌搜索中找到很多关于该主题的信息。我有以下引发错误的代码:

notif.m

#import <stdio.h>
#import <Cocoa/Cocoa.h>
#import <UserNotifications/UserNotifications.h>
#import <objc/runtime.h>

int native_show_notification(char *title, char *msg) {
    UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
    content.title = [NSString stringWithUTF8String:title];
    content.body = [NSString stringWithUTF8String:msg];
    content.sound = [UNNotificationSound defaultSound];

    UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger triggerWithTimeInterval:5 repeats:NO];
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"NOTIFICATION" content:content trigger:trigger];
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];

    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            printf("NOTIFICATION SUCCESS ASDF");
        }
    }];

    return 0;
}

int main() {
    native_show_notification("Foo" , "Bar");
}

Info.plist在同一目录中:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>CFBundleIdentifier</key>
  <string>com.microsoft.VSCode</string>
</dict>
</plist>

这是使用编译的cc -framework Cocoa -framework UserNotifications -o app notif.m。是自动合并的Info.plist,因此不应该存在捆绑问题。

不幸的是,运行后./app出现以下错误:

Assertion failure in +[UNUserNotificationCenter currentNotificationCenter], UNUserNotificationCenter.m:54
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'bundleProxyForCurrentProcess is nil: mainBundle.bundleURL file:///path-to-folder-containing-the-source-files'

我是 MacOS/Objective-C 开发的新手,无法解析此消息。也无法理解我可以在 Google 上找到的内容。任何见解将不胜感激;非常感谢!

4

0 回答 0