Pulling my hair out getting CFNotificationCenterAddObserver
to work in Swift.
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
UnsafePointer<Void>(self),
iosLocked,
"com.apple.springboard.lockcomputer" as CFString,
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
The iOS docs have it listed and I have tried countless iterations on the callback and the unsafe pointer with no success.
The above function call results in this error message, which seems to be the correct init:
Cannot invoke 'init' with an argument list of type '(CFNotificationCenter!, $T4, () -> (), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)'
I also tried bridging to objc as this post here suggests, but without success.
Here is my bridge:
LockNotifierCallback.h:
#import <Foundation/Foundation.h>
@interface LockNotifierCallback : NSObject
+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;
@end
and 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
with updated CFNotificationCenterAddObserver call as follows:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
LockNotifierCallback.notifierProc,
iosLocked,
"com.apple.springboard.lockcomputer" as CFString,
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
and of course LockNotifierCallback.h is in my Bridging header. Error continues:
Cannot convert the expression's type '(CFNotificationCenter!, () -> CFunctionPointer<((CFNotificationCenter!, UnsafeMutablePointer<Void>, CFString!, UnsafePointer<Void>, CFDictionary!) -> Void)>, () -> (), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)' to type 'StringLiteralConvertible'
CFNotificationCenterAddObserver
takes aCFunctionPointer
which you can't really create from Swift (see https://mcmap.net/q/715621/-using-swift-cfunctionpointer-to-pass-a-callback-to-coremidi-api). You can work around it by doing some Objective-C bridging similar to this: https://mcmap.net/q/753032/-objective-c-wrapper-for-cfunctionpointer-to-a-swift-closure – WakerlyiosLocked
is, but it looks like you just have your parameters in the wrong places. This compiles for me:CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, LockNotifierCallback.notifierProc(), "com.apple.springboard.lockcomputer", nil, CFNotificationSuspensionBehavior.DeliverImmediately)
– Wakerly