Created
February 20, 2020 11:24
-
-
Save gali8/17e1a94fabf38d221ba1b42f661f1732 to your computer and use it in GitHub Desktop.
DynamicPushAnswers - handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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