how to use Notification.Name extension from swift 3 to Objective-C
My extension in swift file
extension Notification.Name {
static let purchaseDidFinish = Notification.Name("purchaseDidFinish")
}
@objc extension NSNotification {
public static let purchaseDidFinish = Notification.Name.purchaseDidFinish
}
// OBJECTIVE-C
#import YourProjectName-Swift.h
[NSNotificationCenter.defaultCenter addObserver:self selector:@selector(purchaseDidFinish) name:NSNotification.purchaseDidFinish object:nil];
// SWIFT
NotificationCenter.default.addObserver(self, selector: #selector(purchaseDidFinish), name: .purchaseDidFinish, object: nil)
@objc func purchaseDidFinish(notification: Notification) {
print("purchaseDidFinish")
}
@leanne's answer was super helpful
Notification.Name
doesn't exist in Objective-C. And the Objective-C type NotificationName
is really just an NSString
. To use Swift stuff in Objective-C, the class must be available in both, and can't be a Swift struct (like Notification
or String
, say).
To do what you want, then, you need to have two extensions:
- one for the Swift
Notification.Name
, as you have; and, - one for an Objective-C object (
NSString
, say, or perhapsNSNotification
if you prefer).
1) Add an Objective-C-compatible object extension to your Swift file:
public extension NSNotification {
public static let blahblahblah: NSString = "blahblahblah"
}
Note: in Swift 4, properties must be computed for Objective-C compatibility. That would look like:
@objc public extension NSNotification {
public static var blahblahblah: NSString {
return "blahblahblah"
}
}
Note the var
in the computed property: computed properties can't be immutable, so can't use let
.
2) In the Objective-C file, import Xcode's generated Swift header file (below any other imports):
#import "YourProjectName-Swift.h"
Note: replace YourProjectName
with the actual name of your project. So, if your project is named "CoolGameApp", the Swift header would be "CoolGameApp-Swift.h". If your project name has spaces, like "Cool Game App", replace them with dashes: "Cool-Game-App-Swift.h"
3) Rebuild the project.
Now, you should be able to access the extension in Objective-C:
[[NSNotificationCenter defaultCenter] postNotificationName:NSNotification.blahblahblah object:self];
In addition to the answers here, I had to add @objc to my NSNotification extension before my Obj-C code could see it (Swift 4).