I'd like to create Attendance management app for iOS. The app will have start button, then if it tapped the app would have banner notification to greet you.
The problem is I can't have banner notification while the app is foreground. I'll show my code below. If I want to get a notification, I have to return home screen or run other apps instead.
On my app, Set Notification
button is enable to have notifications, and Start
button is for set notification. I would have notification immediately, but at this moment I have to go back to home, so I set the timing timeInterval: 5
.
ContentView.swift
import SwiftUI
import Foundation
import UserNotifications
struct ContentView: View {
var body: some View {
VStack {
Button(action: { self.setNotification() }) {
Text("Set Notification")
}.padding()
//added here
Button(action: { self.btnSend() }) {
Text("Start")
}.padding()
}
}
func setNotification() -> Void {
UNUserNotificationCenter.current().requestAuthorization(
options: [.alert,.sound,.badge], completionHandler: {didAllow,Error in
print(didAllow) //
})
}
func btnSend() {
print("btnSend")
let content = UNMutableNotificationContent()
content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
content.body = NSString.localizedUserNotificationString(forKey: "Good morning hehe", arguments: nil)
content.sound = UNNotificationSound.default
// Deliver the notification in five seconds.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "FiveSecond",
content: content, trigger: trigger) // Schedule the notification.
let center = UNUserNotificationCenter.current()
center.add(request) { (error : Error?) in
if let theError = error {
// Handle any errors
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Do anyone have nice solutions?