2017-02-03 4 views
1

Я добавляю новые функции с Swift в Objective-C.Objective C observer - как использовать в Swift

У меня есть этот наблюдатель в Objective-C (registration.m):

[[NSNotificationCenter defaultCenter] removeObserver:self name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil]; 

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(confirmSms) name:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil]; 

и в confirm.m:

[[NSNotificationCenter defaultCenter] postNotificationName:NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS object:nil]; 

Как наблюдать это в Swift? Я попытался

NotificationCenter.default.removeObserver(self, 
                name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS, 
                object:nil); 

NotificationCenter.default.addObserver(self, 
               selector:#selector(self.confirmationSmsSent), 
               name: NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS, 
               object: nil); 

И я получаю

Использование неразрешенного идентификатора 'NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS'

Благодарности

// EDIT:

я объявил в Obj-C:

NSString *const NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = @"confirmationSMSSent"; 

Будет ли это по-прежнему работать с этим?

let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS 

И когда я использую

NotificationCenter.default.addObserver(self, selector:#selector(self.confirmationSmsSent(_:)), name: name, object: nil) 

func confirmationSmsSent(notification: NSNotification) { 

} 

я получил ошибку

Значение типа 'MyController' не имеет ни одного члена 'confirmationSmsSent'

на

NotificationCenter.default.addObserver (самость, селектор: #selector (self.confirmationSmsSent (_ :)) Имя: объект: ноль)

+0

http://stackoverflow.com/questions/36910965/how-to-pass-data-using-notificationcentre-in-swift-3-0-and-nsnotificationcenter/36911168#36911168 – Sahil

+0

в файле witch, который вы указали NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS переменная? –

ответ

3

В Swift 3 синтаксис изменен.Вы должны определить переменную NSNotification.Name

let name: NSNotification.Name = NSNotification.Name("Your_Notification_Name_Key_String") //NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS 

//Add Notification 
NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: name, object: nil) 

//Remove Notification Observer 
NotificationCenter.default.removeObserver(self, name: name, object: nil) 

//Your Selector 
func yourSelector(_ notification: Notification) { 
//Code 
} 
+0

и self.yourSelector (_ :) shoud определяется как func yourSelector()? Что должно быть в() как param? На func confirmSmsSent (уведомление: NSNotification) {} Я получаю ошибку селектора ** Значение типа «MyController» не имеет подтверждения для членаSmsSent '** – David

+0

@David Pls проверяет отредактированный ответ –

+1

@ sohil-r-memon Спасибо вы! – David

1

Это потому, что вы еще не объявили NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS.

Обычно имя уведомления - это всего лишь строка, кстати, вы должны отнести его к вложенному типу NSNotification.Name.

let NOTIFICATION_SERVER_SENT_CONFIRMATION_SMS = NSNotification.Name("<some string>") 
1

Самый полезный стремительной - lije код расширения

extension Notification.Name { 
static let someNewName = "ThatsItImAwsome" 
} 

Использование внутри поста:

.someNewKey

это:

NotificationCenter.default.addObserver(self, selector:#selector(self.yourSelector(_:)), name: .someNewKey, object: nil) 
Смежные вопросы