无法将类型为“NSNotification.Name”的值转换为预期的参数类型“NSKeyValueObservingOptions”

3
在NMAPositioningManager.h中有这个常量:
FOUNDATION_EXPORT NSString *const NMAPositioningManagerDidUpdatePositionNotification;

这是我的 Swift 代码

NotificationCenter.addObserver(self, forKeyPath: "positionDidUpdate", options: NSNotification.Name.NMAPositioningManagerDidUpdatePosition, context: NMAPositioningManager.shared())

受Obj-C中的这个示例启发:

[[NSNotificationCenter defaultCenter] addObserver:self
 selector:@selector(positionDidUpdate)
 name:NMAPositioningManagerDidUpdatePositionNotification
 object:[NMAPositioningManager sharedNMAPositioningManager]];

我遇到了字段选项错误:

NavigationViewController.swift:30:84: 无法将类型“NSNotification.Name”的值转换为预期的类型“NSKeyValueObservingOptions”

enter image description here

请问我应该输入什么来使我的Swift代码正常工作?
编辑:请使用NotificationCenter代替Notification。

1
只是为了澄清一下。你的Objective C示例使用了NSNotificationCenter,而你的Swift代码使用了NSNotification。你想使用NSNotification还是你想使用NSNotificationCenter? - pbodsk
事实上,我需要使用NotificationCenter。我已经编辑了我的答案,但是仍然出现相同的错误。 - Kevin ABRIOUX
2个回答

4
您应该在default单例上调用addObserver..方法。 正确写法为:
NotificationCenter.default.addObserver(self, selector: #selector(positionDidUpdate), name: NSNotification.Name.NMAPositioningManagerDidUpdatePosition, object: NMAPositioningManager.shared())

就这样,我在“addObserver”中使用了错误的句子。非常感谢您的时间。 - Kevin ABRIOUX

2

已更新为 Swift 5.4

NotificationCenter.default.addObserver(self,
                                       selector: #selector(doThisWhenNotify),
                                       name: NSNotification.Name("notificationKey"),
                                       object: nil)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接