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

时间:2014-10-29 17:31:03

标签: ios swift notifications darwin

拉我的头发让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'

2 个答案:

答案 0 :(得分:9)

我遇到了DarwinNotifications的一些问题,你可以尝试使用这个包装类 只需在桥接文件中包含头文件即可。你可以在swift中使用它。

DarwinNotificationsManager.h:

#import <Foundation/Foundation.h>

#ifndef DarwinNotifications_h
#define DarwinNotifications_h

@interface DarwinNotificationsManager : NSObject

@property (strong, nonatomic) id someProperty;

+ (instancetype)sharedInstance;

- (void)registerForNotificationName:(NSString *)name callback:(void (^)(void))callback;
- (void)postNotificationWithName:(NSString *)name;

@end

#endif

DarwinNotificationsManager.m:

#import <Foundation/Foundation.h>
#import "DarwinNotificationsManager.h"


@implementation DarwinNotificationsManager {
    NSMutableDictionary * handlers;
}

+ (instancetype)sharedInstance {
    static id instance = NULL;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        handlers = [NSMutableDictionary dictionary];
    }
    return self;
}

- (void)registerForNotificationName:(NSString *)name callback:(void (^)(void))callback {
    handlers[name] = callback;
    CFNotificationCenterRef center = CFNotificationCenterGetDarwinNotifyCenter();
    CFNotificationCenterAddObserver(center, (__bridge const void *)(self), defaultNotificationCallback, (__bridge CFStringRef)name, NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
}

- (void)postNotificationWithName:(NSString *)name {
    CFNotificationCenterRef center = CFNotificationCenterGetDarwinNotifyCenter();
    CFNotificationCenterPostNotification(center, (__bridge CFStringRef)name, NULL, NULL, YES);
}

- (void)notificationCallbackReceivedWithName:(NSString *)name {
    void (^callback)(void) = handlers[name];
    callback();
}

void defaultNotificationCallback (CFNotificationCenterRef center,
                 void *observer,
                 CFStringRef name,
                 const void *object,
                 CFDictionaryRef userInfo)
{
    NSLog(@"name: %@", name);
    NSLog(@"userinfo: %@", userInfo);

    NSString *identifier = (__bridge NSString *)name;
    [[DarwinNotificationsManager sharedInstance] notificationCallbackReceivedWithName:identifier];
}


- (void)dealloc {
    CFNotificationCenterRef center = CFNotificationCenterGetDarwinNotifyCenter();
    CFNotificationCenterRemoveEveryObserver(center, (__bridge const void *)(self));
}


@end

在swift中你可以像这样使用它:

let darwinNotificationCenter = DarwinNotificationsManager.sharedInstance()
darwinNotificationCenter.registerForNotificationName("YourNotificationName"){
            //code to execute on notification
}

答案 1 :(得分:1)

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

这些文件放置在App和扩展程序共享的库中。该应用程序使用ExtensionListener,扩展程序使用ExtensionEvent。

final public class ExtensionListener: NSObject {

    // the inter-process NotificationCenter
    private let center = CFNotificationCenterGetDarwinNotifyCenter()
    private var listenersStarted = false
    fileprivate static let notificationName = "com.example.CrossProcessExtensionAction" as CFString

    public override init() {
        super.init()
        // listen for an action in the Share Extension
        startListeners()
    }

    deinit {
        // don't listen anymore
        stopListeners()
    }

    //    MARK: listening
    fileprivate func startListeners() {
        if !listenersStarted {
            self.listenersStarted = true
            CFNotificationCenterAddObserver(center, Unmanaged.passRetained(self).toOpaque(), { (center, observer, name, object, userInfo) in
                // send the equivalent internal notification
                NotificationCenter.default.post(name: NSNotification.Name.SomeInternalExtensionAction, object: nil)
            }, Self.notificationName, nil, .deliverImmediately)
        }
    }

    fileprivate func stopListeners() {
        if listenersStarted {
            CFNotificationCenterRemoveEveryObserver(center, Unmanaged.passRetained(self).toOpaque())
            listenersStarted = false
        }
    }
}

final public class ExtensionEvent: NSObject {
    public static func post() {
        CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(), CFNotificationName(rawValue: ExtensionListener.notificationName), nil, nil, true)
    }
}