先上自己适配好的代码
1、h文件
#ifndef CNOTIFYMACBOX_H
#define CNOTIFYMACBOX_H
#ifdef Q_OS_MACOS
#include <QObject>
#include "data_struct/data_struct.h"
class CNotifyMacBox : public QObject {
Q_OBJECT
public:
static void createMacNotifyBox(const RecentSessShowInfo &showInfo, bool isAtMe);
private:
CNotifyMacBox() = default;
~CNotifyMacBox() = default;
};
#endif
#endif // CNOTIFYMACBOX_H
2、mm文件
#include "notify_mac_box.h"
#ifdef Q_OS_MACOS
#include <QtMac>
#include <Cocoa/Cocoa.h>
#include <CoreFoundation/CoreFoundation.h>
#include <objc/objc.h>
#include <objc/objc-runtime.h>
#include <objc/message.h>
#include "session_model.h"
#include "avatar_loader.h"
#include "ui/controller/main_wnd_controller.h"
@interface ViewController : NSObject<NSUserNotificationCenterDelegate>
@end
@implementation ViewController
- (BOOL)userNotificationCenter:(NSUserNotificationCenter *)center
shouldPresentNotification:(NSUserNotification *)notification {
return YES;
}
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:self];
}
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didDeliverNotification:(NSUserNotification *)notification {
}
- (void) userNotificationCenter:(NSUserNotificationCenter *)center didActivateNotification:(NSUserNotification *)notification {
[NSApp activateIgnoringOtherApps:YES];
NSString *sessId = [notification.userInfo valueForKey:@"sessId"];
if (!QString::fromNSString(sessId).isEmpty()) {
g_appModel->GetSessionModel()->OpenSess("", QString::fromNSString(sessId));
feloApp->GetMainFrmController()->ActiveMainWnd();
}
}
- (void) dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
[super dealloc];
}
@end
void CNotifyMacBox::createMacNotifyBox(const RecentSessShowInfo &showInfo, bool isAtMe) {
auto pixmap = AvatarLoader::LoadPixmap(showInfo.logoPath, 60);
QString textStr = showInfo.showContent;
if (isAtMe) {
textStr.prepend(QObject::tr("[You're mentioned]") + " ");
}
NSUserNotification *userNotification = [[NSUserNotification alloc] init];
userNotification.title = showInfo.showTitle.toNSString();
userNotification.informativeText = textStr.toNSString();
userNotification.contentImage = QtMac::toNSImage(pixmap);
userNotification.hasActionButton = NO;
userNotification.userInfo = @ {@"sessId": (showInfo.sessId.toNSString())};
userNotification.soundName = NSUserNotificationDefaultSoundName;
ViewController *vc = [[ViewController alloc] init];
[[NSUserNotificationCenter defaultUserNotificationCenter] setDelegate:vc];
[[NSUserNotificationCenter defaultUserNotificationCenter] deliverNotification:userNotification];
}
#endif
外部C++调用createMacNotifyBox这一接口即可,
投递事件通过defaultUserNotificationCenter,先设置一个自定义的代理(需要继承NSObject<NSUserNotificationCenterDelegate>),再去投递一个自定义的NSUserNotification即可收到原生的推送,若想做到点击推送消息和软件进行交互,则需要重写didActivateNotification方法