2015-09-12 4 views
3

Попытка отправить уведомление с объектива c и получить в быстром сообщении. Я вижу никакой ошибки от отправителя или получателя и функции не не вызывается в целевой вид контроллераотправить уведомление от objectivec и получить в swift

ViewController 1: Цель с

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

ViewController 2: быстрое

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") 

} 
+0

, что вы имеете в виду, посылая из OBJ с и, неточности на скор lol –

+0

Я имел в виду отправку уведомлений с объектного кода c и попытку получить его из swift code.sorry для опечатка. проверьте вставленный частичный код. Сообщите мне, требуется ли дополнительная информация. Оцените свой быстрый ответ – Sandeep

+1

Добавьте примечание @objc над 'receiveNotification', если у вас возникли проблемы. В противном случае ваш код выглядит отлично. –

ответ

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" 

И в вашем SecondViewController.m добавить этот код, когда вы вернетесь к вашей быстрой ViewController.

- (IBAction)goBack:(id)sender { 

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

Для дополнительной информации проверьте THIS образец проекта.

Обновление:

Если первый контроллер является объективным с и второй/целевой контроллер скор.

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) 
} 

Bridging-header.h

#import "FirstViewController.h" 

Sample code

+0

Немного смущен. Мой первый контроллер - объектив c, а второй/целевой контроллер - быстрый. Тем не менее предложение применимо – Sandeep

+0

View Controller 1: Objcdetailed если (self.profile) { [[NSNotificationCenter defaultCenter] postNotificationName: @ "loginViewDidFinish" объект: само USERINFO: self.profile]; } UIStoryboard * mainStoryboard = [UIStoryboard раскадровкаWithName: @ "Main" bundle: nil]; UIViewController * vc = [mainStoryboard instantiateViewControllerWithIdentifier: @ "LoginViewController"]; [self presentModalViewController: vc animated: YES]; – Sandeep

+0

Извините, что смутил вас. Первым контроллером является цель c, которая является отправителем уведомления. Регулятор приемника является быстрым. Ваши примеры кода очень полезны, хотя – Sandeep

2

В 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 { 

} 
Смежные вопросы