Skip to content

Instantly share code, notes, and snippets.

@stinger
Created November 17, 2016 14:28
Show Gist options
  • Save stinger/435d1ce6f9acc8121922f9f35c3c2527 to your computer and use it in GitHub Desktop.
Save stinger/435d1ce6f9acc8121922f9f35c3c2527 to your computer and use it in GitHub Desktop.
Swift 3: ios10 Local notifications
func showPushNotification(title: String, details: String) {
if #available(iOS 10.0, *) {
let interval = TimeInterval(1)
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: interval, repeats: false)
let content = UNMutableNotificationContent()
content.title = title
content.body = details
let req = UNNotificationRequest(identifier: "localPushNotification", content: content, trigger: trigger)
let center = UNUserNotificationCenter.current()
center.getNotificationSettings(completionHandler: { settings in
switch settings.authorizationStatus {
case .notDetermined:
center.requestAuthorization(options: [.alert, .sound], completionHandler: { ok, err in
if let err = err {
print(err)
return
}
if ok {
center.add(req, withCompletionHandler: nil)
}
})
case .denied: break
case .authorized:
center.add(req, withCompletionHandler: nil)
break
}
})
} else {
// handle old iOS versions
}
}
// App Delegate
@available(iOS 10.0, *)
extension AppDelegate: UNUserNotificationCenterDelegate {
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
if response.actionIdentifier == UNNotificationDefaultActionIdentifier {
// do stuff
completionHandler()
}
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.sound, .alert])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment