如何在iOS的Swift中正确使用CFNotificationCenterAddObserver

问题描述 投票:10回答:2

[拔出头发让CFNotificationCenterAddObserver在Swift中工作。

        CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
        UnsafePointer<Void>(self),
        iosLocked,
        "com.apple.springboard.lockcomputer" as CFString,
        nil,
        CFNotificationSuspensionBehavior.DeliverImmediately)

iOS docs列出了它,我尝试了无数次回调和不安全指针的迭代,但均未成功。

上面的函数调用导致此错误消息,这似乎是正确的init:

Cannot invoke 'init' with an argument list of type '(CFNotificationCenter!, $T4, () -> (), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)'

[我也尝试按照this post here的建议桥接到objc,但没有成功。

这是我的桥梁:

LockNotifierCallback.h:

#import <Foundation/Foundation.h>

@interface LockNotifierCallback : NSObject

+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;

@end

和LockNotifierCallback.m:

#import "LockNotifierCallback.h"

static void lockcompleteChanged(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo) {
    NSLog(@"success");
}

@implementation LockNotifierCallback


+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc {
    return lockcompleteChanged;
}

@end

具有更新的CFNotificationCenterAddObserver调用,如下所示:

CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
        LockNotifierCallback.notifierProc,
        iosLocked,
        "com.apple.springboard.lockcomputer" as CFString,
        nil,
        CFNotificationSuspensionBehavior.DeliverImmediately)

当然还有LockNotifierCallback.h在我的Bridging标头中。错误继续:

Cannot convert the expression's type '(CFNotificationCenter!, () -> CFunctionPointer<((CFNotificationCenter!, UnsafeMutablePointer<Void>, CFString!, UnsafePointer<Void>, CFDictionary!) -> Void)>, () -> (), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)' to type 'StringLiteralConvertible'
ios swift notifications darwin
2个回答
9
投票

我在DarwinNotifications中遇到了一些问题,您可以尝试使用此包装器类只需在桥接文件中包含头文件即可。而且您可以快速使用它。

DarwinNotificationsManager.h:


0
投票

我编写此代码是为了将来自共享扩展的通知传递给其父应用,而在iPadOS中,两者可以同时处于活动状态。

© www.soinside.com 2019 - 2024. All rights reserved.