Skip to content

Instantly share code, notes, and snippets.

@gali8
Created February 20, 2020 11:24
Show Gist options
  • Save gali8/17e1a94fabf38d221ba1b42f661f1732 to your computer and use it in GitHub Desktop.
Save gali8/17e1a94fabf38d221ba1b42f661f1732 to your computer and use it in GitHub Desktop.
DynamicPushAnswers - handler
func prepareNotification(content: UNNotificationContent, userInfo: [AnyHashable: Any], completionHandler: @escaping (UNNotificationPresentationOptions) -> Void){
// Register the notification type.
let notificationCenter = UNUserNotificationCenter.current()
var json = JSON(userInfo)
guard let data = json["data"].dictionary else {
completionHandler([ .alert, .sound, .badge ])
return
}
let alreadyRequested = data["PushManagerPrepared"]?.bool ?? false
guard alreadyRequested == false else {
completionHandler([ .alert, .sound, .badge ])
return
}
guard let question = data["question"]?.dictionary, let questionId = question["id"]?.int, let answers = question["answers"]?.array, !answers.isEmpty else {
completionHandler([ .alert, .sound, .badge ])
return
}
let acts = answers.map { (answer) -> UNNotificationAction in
let action = UNNotificationAction(identifier: String(answer["id"].int!), title: answer["text"].string!, options: [.foreground])
return action
}
let category = UNNotificationCategory(identifier: "DynamicPushAnswersInQuestion" + String(questionId), actions: acts, intentIdentifiers: [], options: [])
// Register the notification type.
notificationCenter.setNotificationCategories([category])
let newContent = UNMutableNotificationContent()
newContent.title = content.title
newContent.body = content.body
newContent.subtitle = content.subtitle
newContent.sound = content.sound
json["data"]["PushManagerPrepared"] = true
newContent.userInfo = json.dictionaryObject!
newContent.categoryIdentifier = category.identifier
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 2, repeats: false)
let newRequest = UNNotificationRequest(identifier: category.identifier, content: newContent, trigger: trigger)
//add new notification with category
notificationCenter.add(newRequest) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
completionHandler([])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment