发送来自objectivec的通知并在swift中接收

时间:2015-09-12 05:41:51

标签: ios objective-c swift

尝试从目标c发送通知并在swift中接收。我看到发送方或接收方没有错误,并且在目标视图控制器中没有调用函数

ViewController 1:Objective c

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"notifyme"
     object:self
     userInfo:self.profile];

ViewController 2:swift

override func viewDidLoad() {
    super.viewDidLoad()
    print("view did load")
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveNotification:", name: "notifyme", object: nil)

}

func receiveNotification(ns: NSNotification){
    print("Received Notification")

}

2 个答案:

答案 0 :(得分:3)

在Swift3中,我解决了这个问题

发送OC

[[NSNotificationCenter defaultCenter] postNotificationName:"You NotificationName" object:nil];

接收Swift 3

func applicationDidBecomeActive(_ application: UIApplication) {
    NotificationCenter.default.addObserver(self, selector: #selector(self.handleNotification), name: NSNotification.Name.init(rawValue: "You NotificationName"), object: nil)
}
func handleNotification() -> Void {

}

答案 1 :(得分:2)

请按照以下步骤操作:

首先在你的ViewController.swift中添加它,这是你的第一个视图:

override func viewDidLoad() {
    super.viewDidLoad()
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "receiveNotification:", name: "notifyme", object: nil)
}

func receiveNotification(ns: NSNotification){
    print("Received Notification")
}

之后在Obj-c中添加一个新类,不要忘记为该类创建桥接头。

在桥接头文件中添加以这种方式导入SecondViewController:

#import "SecondViewController.h"

当您回到swift viewController时,在SecondViewController.m添加此代码。

- (IBAction)goBack:(id)sender {

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"notifyme"
     object:nil
     userInfo:nil];
    [self dismissViewControllerAnimated:NO completion:nil];
}

有关详细信息,请查看THIS示例项目。

<强>更新

如果第一个控制器是目标c而第二个/目标控制器是快速的。

<强> FirstViewController.m

#import "FirstViewController.h"

@interface FirstViewController ()

@end

@implementation FirstViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(receiveTestNotification:)
                                                 name:@"TestNotification"
                                               object:nil];
}

- (void) receiveTestNotification:(NSNotification *) notification
{
    if ([[notification name] isEqualToString:@"TestNotification"])
        NSLog (@"Successfully received the test notification!");
}
@end

<强> SecondViewController.swift

@IBAction func goBack(sender: AnyObject) {

    NSNotificationCenter.defaultCenter().postNotificationName("TestNotification", object: nil, userInfo: nil)
    self.dismissViewControllerAnimated(true, completion: nil)
}

<强>桥接-Header.h

#import "FirstViewController.h"

<强> Sample code