Skip to content

Instantly share code, notes, and snippets.

@runys
Last active August 4, 2021 10:13
Show Gist options
  • Save runys/a1797d7200d0d1f11054ccccbcb8f8c3 to your computer and use it in GitHub Desktop.
Save runys/a1797d7200d0d1f11054ccccbcb8f8c3 to your computer and use it in GitHub Desktop.
Sample code for the article User Interaction with Notifications with async/await (https://www.createwithswift.com/p/6c6bca46-a2b9-4f9e-97c5-a061f637e45c/) on Create with Swift (https://www.createwithswift.com)
// CoffeeNotifications.swift
// Created by Tiago Pereira on 23/07/21.
import Foundation
import UserNotifications
class CoffeeNotifications {
var isAuthorizedToNotify: Bool {
get async {
let notificationCenter = UNUserNotificationCenter.current()
let currentSettings = await notificationCenter.notificationSettings()
return currentSettings.authorizationStatus == .authorized
}
}
func requestAuthorizationForNotifications() async throws -> Bool {
if await self.isAuthorizedToNotify {
print("🟢 Notifications are authorized")
return true
} else {
print("💬 Requesting authorizations for notifications")
let notificationCenter = UNUserNotificationCenter.current()
let authorizationOptions: UNAuthorizationOptions = [.alert]
do {
return try await notificationCenter.requestAuthorization(options: authorizationOptions)
} catch {
throw error
}
}
}
func scheduleNotifications() async {
// Create the content of the notification
let notificationContent = UNMutableNotificationContent()
notificationContent.title = "It is coffee time!"
notificationContent.subtitle = "Everyday at 10:00 is time to a break."
notificationContent.body = "Our favorite café in Naples is the Napoli Café. Try the cappuccino!"
// 9. Assign the category identifier to the notification content
notificationContent.categoryIdentifier = "COFFEE_TIME"
// Set up the notification trigger
let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: 10, repeats: false)
// Create the notification identifier
let notificationIdentifier = "COFFEE_TIME_NOTIFICATION"
// Create the notification request
let notificationRequest = UNNotificationRequest(identifier: notificationIdentifier,
content: notificationContent,
trigger: notificationTrigger)
// Schedule the notification
let notificationCenter = UNUserNotificationCenter.current()
do {
try await notificationCenter.add(notificationRequest)
print("🟢 Coffee Time notification was scheduled.")
} catch {
print("⛔️ \(error.localizedDescription)")
}
}
}
// CoffeeTimeApp.swift
// Created by Tiago Pereira on 23/07/21.
import SwiftUI
@main
struct CoffeeTimeApp: App {
// 8. Set up our class as the application delegate
@UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
// 1. Create a new class called AppDelegate
class AppDelegate: NSObject, UIApplicationDelegate {
// 2. Add the method defined by the UIApplicationDelegate protocol
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
// 12. Set up the delegate object of the notification center
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
// 7. Calling our function
self.setUpCoffeeNotificationCategory()
return true
}
// 3. Function to set up your notification category and actions
func setUpCoffeeNotificationCategory() {
// 4. Define the custom actions
let onMyWayAction = UNNotificationAction(identifier: "ACCEPT_ACTION", title: "On My Way", options: UNNotificationActionOptions(rawValue: 0))
let cantGoNowAction = UNNotificationAction(identifier: "DECLINE_ACTION", title: "Can't Go", options: UNNotificationActionOptions(rawValue: 0))
// 5. Define the notification category
let coffeeTimeCategory = UNNotificationCategory(
identifier: "COFFEE_TIME",
actions: [onMyWayAction, cantGoNowAction],
intentIdentifiers: [],
hiddenPreviewsBodyPlaceholder: "Unlock for coffee.",
options: .customDismissAction
)
// 6. Register the notification category
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.setNotificationCategories([coffeeTimeCategory])
print("🟢 Coffee Time category was registered.")
}
}
// 10. Create an extension of AppDelegate that conforms to the UNUserNotificationCenterDelegate protocol
extension AppDelegate: UNUserNotificationCenterDelegate {
// 11. Implement the method that handles notification responses
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {
let categoryIdentifier = response.notification.request.content.categoryIdentifier
let actionIdentifier = response.actionIdentifier
print("🟣 Notification Category: \(categoryIdentifier)")
print("🟣 Action Identifier: \(actionIdentifier)")
}
}
// ContentView.swift
// Created by Tiago Pereira on 23/07/21.
import SwiftUI
struct ContentView: View {
var body: some View {
Text("Coffee Time Notifications App")
.padding()
.task {
await self.testingNotifications()
}
}
private func testingNotifications() async {
let coffeeNotifications = CoffeeNotifications()
do {
_ = try await coffeeNotifications.requestAuthorizationForNotifications()
await coffeeNotifications.scheduleNotifications()
} catch {
print("Authorization Error: \(error.localizedDescription)")
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment