2017-01-11 11 views
1

Привет, я новичок в разработке приложений для iOS. Я использую Swift 3.0.Можем ли мы обновить ViewController от didRegisterForRemoteNotificationsWithDeviceToken, проверив isRegisteredForLocalNotifications

В моем приложении я извлекаю токен устройства, и я перехожу на свой сервер. передать значение токена из Appdelegate в UIViewController. Я использую UserDefaults.standard. и он работает нормально. Во время загрузки первого приложения я показываю приглашение push-уведомления системы. Если пользователь нажмет OK (разрешить) или не разрешить. приложение проверяет его, используя следующий код.

//Checking Notification State 
    let isRegisteredForLocalNotifications = UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false 

    if isRegisteredForLocalNotifications{ 
     print("Notification allow") 
    }else{ 
     print("Notification Don't allow") 
    } 

Примечание: Приведенный выше код работает отлично в didRegisterForRemoteNotificationsWithDeviceToken.

У меня возникла следующая проблема с вышеуказанным кодом.

1) если я использую тот же код в ViewController, его работаю, но мое приложение не ждет результата запроса push-уведомления системы. Я получаю результаты в AppDelegate.

So как перезагрузить ViewController из didRegisterForRemoteNotificationsWithDeviceToken? есть ли способ сделать это.

2) Могу ли я приостановить viewController, пока пользователь не ответит на запрос уведомления о нажатии кнопки системы. Но я не уверен, что выше код будет работать в ViewController или нет.

Просьба сообщить. Спасибо за помощь.

ответ

1

Для первой части вашей проблемы, вы можете создать наблюдатель:

NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil) 

функция, справиться с этим будет выглядеть следующим образом:

func methodOfReceivedNotification(notification: Notification){ 
    //Take Action on Notification 
} 

, а затем вы можете назвать его следующим образом:

NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil) 

вы можете вызвать вышеуказанный код всякий раз, когда вы хотите обновить ViewController

1

Вы можете обновить контроллер просмотра от didRegisterForRemoteNotificationsWithDeviceToken? по почте.

let notificationIdentifier: String = "NotificationIdentifier" 

//write this to didRegisterForRemoteNotificationsWithDeviceToken 
// Post notification 
    NotificationCenter.default.post(name: notificationName, object: nil) 
//write this to your View Controller 
let notificationIdentifier: String = "NotificationIdentifier" 

// Register to receive notification 
NotificationCenter.default.addObserver(self, selector:#selector(YourClassName.methodOfReceivedNotification), name: notificationName, object: nil) 



// Stop listening notification 
NotificationCenter.default.removeObserver(self, name: notificationName, object: nil); 


func methodOfReceivedNotification(notification: Notification) { 
}