【发布时间】:2014-10-29 17:31:03
【问题描述】:
让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'
【问题讨论】:
-
CFNotificationCenterAddObserver需要一个CFunctionPointer,你不能从 Swift 中真正创建它(参见 stackoverflow.com/a/25514748/3300036)。您可以通过执行一些类似于此的 Objective-C 桥接来解决它:stackoverflow.com/a/26139259/3300036 -
谢谢马克,但为什么它会在 ios 文档中快速声明? developer.apple.com/Library/ios/documentation/CoreFoundation/…
-
你仍然可以在 Swift 中使用它,你只需要传递一个在 C 或 Objective-C 中定义的函数,而不是一个 Swift 闭包函数。
-
再次感谢马克。我仍然卡住了,请参阅上面编辑的 Q。
-
我不确定
iosLocked是什么,但看起来您只是将参数放在错误的位置。这为我编译:CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), nil, LockNotifierCallback.notifierProc(), "com.apple.springboard.lockcomputer", nil, CFNotificationSuspensionBehavior.DeliverImmediately)
标签: ios swift notifications darwin