verwenden Zieht meine Haare aus CFNotificationCenterAddObserver
zu arbeiten in Swift.Wie man korrekt CFNotificationCenterAddObserver in Swift für iOS
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
UnsafePointer<Void>(self),
iosLocked,
"com.apple.springboard.lockcomputer" as CFString,
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
Die iOS docs haben sie aufgelistet und ich habe unzählige Iterationen auf dem Rückruf und die unsicheren Zeiger ohne Erfolg versucht.
Der Aufruf über Funktionsergebnisse in dieser Fehlermeldung, die die korrekte init zu sein scheint:
Cannot invoke 'init' with an argument list of type '(CFNotificationCenter!, $T4,() ->(), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)'
ich als this post here schlägt ObjC Überbrückung auch versucht, aber ohne Erfolg.
Hier ist meine Brücke:
LockNotifierCallback.h:
#import <Foundation/Foundation.h>
@interface LockNotifierCallback : NSObject
+ (void(*)(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo))notifierProc;
@end
und 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
mit Aufruf aktualisiertem CFNotificationCenterAddObserver wie folgt:
CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(),
LockNotifierCallback.notifierProc,
iosLocked,
"com.apple.springboard.lockcomputer" as CFString,
nil,
CFNotificationSuspensionBehavior.DeliverImmediately)
und natürlich LockNotifierCallback.h ist in meinem Bridging-Header. Fehler weiter:
Cannot convert the expression's type '(CFNotificationCenter!,() -> CFunctionPointer<((CFNotificationCenter!, UnsafeMutablePointer<Void>, CFString!, UnsafePointer<Void>, CFDictionary!) -> Void)>,() ->(), CFString, NilLiteralConvertible, CFNotificationSuspensionBehavior)' to type 'StringLiteralConvertible'
'CFNotificationCenterAddObserver' nimmt einen' CFunctionPointer' die Sie können nicht wirklich von Swift erstellen (siehe http://StackOverflow.com/a/25514748/3300036). Sie können umgehen, indem Sie einige Objective-C-Bridging ähnlich wie folgt tun: http://stackoverflow.com/a/26139259/3300036 –
Danke Mark, aber warum würde es unter einer schnellen Deklaration in den IOS-Dokumenten sein? https://developer.apple.com/Library/ios/documentation/CoreFoundation/Reference/CFNotificationCenterRef/index.html#//apple_ref/c/func/CFNotificationCenterAddObserver – zooster
Sie können es immer noch von Swift verwenden, Sie müssen es nur übergeben eine Funktion, die in C oder Objective-C definiert ist und keine Swift-Funktion des Abschlusses. –