Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Notification.Name extension from Swift to Objective-C?

I created an extension for Notification.Name as below:

public extension Notification.Name {     public static let blahblahblah = Notification.Name(rawValue: "blahblahblah") } 

Now I want to use this extension in Objective-C, but it's not accessible even if its public.

How can I access and use this Swift extension in both Objective-C and Swift?

Previously I was using constant values in Objective-C, but now I'm upgrading my code and want to use this extension.

like image 631
BARS Avatar asked Oct 18 '17 20:10

BARS


People also ask

Is Swift is extension of Objective-C?

You can write a Swift extension and use it in Objective-C code.

What is Nsnotification name?

A structure that defines the name of a notification.

How do I add notification observer in Swift 4?

First, register an observer for a notification with: addObserver(_:selector:name:object:) Then, post a notification with post(name:object:userInfo:) … … after which your selector is called. And don't forget to remove the observer with removeObserver()


1 Answers

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

like image 87
Warif Akhand Rishi Avatar answered Sep 30 '22 10:09

Warif Akhand Rishi