Я пытаюсь определить действие уведомления пользователя с помощью ViewController. По моему мнению, в App Delegate должно быть настроено уведомление с действиями.swift, UIUserNotificationAction from view controller вместо делегата приложения
Так here's мой App Делегат:
class AppDelegate: UIResponder, UIApplicationDelegate {
enum Actions:String{
case confirmunlock = "CONFIRMUNLOCK_ACTION"
}
var categoryID:String {
get{
return "CONFRIMUNLOCK_CATEGORY"
}
}
// Register notification settings
func registerNotification() {
// 1. Create the actions **************************************************
// confirmunlock Action
let confirmunlockAction = UIMutableUserNotificationAction()
confirmunlockAction.identifier = Actions.confirmunlock.rawValue
confirmunlockAction.title = "Öffnen"
confirmunlockAction.activationMode = UIUserNotificationActivationMode.Background
confirmunlockAction.authenticationRequired = false
confirmunlockAction.destructive = false
// 2. Create the category ***********************************************
// Category
let confirmunlockCategory = UIMutableUserNotificationCategory()
confirmunlockCategory.identifier = categoryID
// A. Set actions for the default context
confirmunlockCategory.setActions([confirmunlockAction],
forContext: UIUserNotificationActionContext.Default)
// B. Set actions for the minimal context
confirmunlockCategory.setActions([confirmunlockAction],
forContext: UIUserNotificationActionContext.Minimal)
// 3. Notification Registration *****************************************
let types: UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Sound]
let settings = UIUserNotificationSettings(forTypes: types, categories: NSSet(object: confirmunlockCategory) as? Set<UIUserNotificationCategory>)
UIApplication.sharedApplication().registerUserNotificationSettings(settings)
}
// MARK: Application Delegate
func application(application: UIApplication,
handleActionWithIdentifier identifier: String?,
forLocalNotification notification: UILocalNotification,
completionHandler:() -> Void) {
// Handle notification action *****************************************
if notification.category == categoryID {
let action:Actions = Actions(rawValue: identifier!)!
switch action{
case Actions.confirmunlock:
print("Well done!")
}
}
completionHandler()
}
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
registerNotification()
return true
}
Это хорошо работает. Когда я добавляю «notification.category = categoryID» в одно из моих LocalNotifications, он записывает «Хорошо». Теперь действие, которое я бы хотел вызвать, должно фактически вызываться из контроллера вида. У него много переменных, и вы должны сначала войти в систему, чтобы получить доступ к серверу, чтобы вызвать действие и т. Д. Как я могу это сделать? Когда я помещаю эту функцию в свой контроллер, действие не набирается:
func application(application: UIApplication,
handleActionWithIdentifier identifier: String?,
forLocalNotification notification: UILocalNotification,
completionHandler:() -> Void) {
// Handle notification action *****************************************
if notification.category == categoryID {
let action:Actions = Actions(rawValue: identifier!)!
switch action{
case Actions.confirmunlock:
print("Well done!")
}
}
completionHandler()
}
Большое спасибо! Stephan
Привет, я попробовать. К сожалению, функция диспетчера просмотра не работает с делегатом приложения. Я уже начинаю с того, что выбранная строка не переносится. Таким образом, это работает в моем ViewController (selectedlock - это строка выбора picker): 'let key = keys [selectedlock]' В делете делегата это всегда дает мне 0 как выбранную блокировку, независимо от того, что я выбрал в представлении выбора: 'print (ViewController(). Selectlock) ' – StephanD
Я предполагаю, что ваша архитектура приложения не готова к использованию так, и вам кажется, вам нужно выяснить, как экземпляры экземпляров и их функции могут взаимодействовать друг с другом. Например. вы не должны полагаться на глобальные переменные ('selectedLock' в' ViewController') для взаимодействия между объектами. Одним из способов может быть использование уведомлений: http://nshipster.com/nsnotification-and-nsnotificationcenter/ –
Могу ли я использовать NSNotificationCenter для запуска этого действия в моем ViewController? – StephanD