[SwiftUI]本地通知


先创建一个通知管理器,请求通知权限、检查通知权限 和 创建通知内容。

import Foundation
import UserNotifications

class NotificationManager: ObservableObject {
    
    static let shared = NotificationManager()
    private var limitFirst: Bool = false
    @Published var showingAlert = false // 控制Alert弹窗
    var notificationSettings: UNNotificationSettings?

    /// 请求通知权限
    func requestAuthorization() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("All set!")
            } else if let error = error {
                print(error.localizedDescription)
            } else { // 未开启权限
                if self.limitFirst {
                    self.checkAuthourization()
                }
                self.limitFirst = true
            }
        }
    }
    
    /// 检查通知权限
    func checkAuthourization() {
        UNUserNotificationCenter.current().getNotificationSettings { settings in
            DispatchQueue.main.async {
                self.notificationSettings = settings
                // Check if permission is not granted
                if settings.authorizationStatus != .authorized {
                    self.showingAlert = true
                }
            }
        }
    }
    
    /// 创建通知内容
    func scheduleNotification() {
        let content = UNMutableNotificationContent()
        content.title = "Title"
        content.subtitle = "Subtitle"
        content.body = "Your notification body"
        content.sound = UNNotificationSound.default

        // 设置触发器
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: false)

        // 创建通知请求
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

        // 将请求添加到通知中心
        UNUserNotificationCenter.current().add(request) { error in
            if let error = error {
                print("Error: \(error.localizedDescription)")
            }
        }
    }
    
}

使用本地通知,在开关开启时请求权限,若通知权限是拒绝状态就弹窗通知去设置开启。

状态为true时,随后调度通知,只有在权限开启时APP才能收到通知。

注意,APP进入后台或者杀掉APP都能收到推送通知信息。

struct SettingItemView: View {
    @State var switchState: Bool = false
    // 检查未开启通知权限后弹出去设置的弹窗
    @ObservedObject var notificationManager = NotificationManager.shared

    var body: some View {
        HStack {  
        	Spacer()              
            Toggle(isOn: $switchState) {
            	Text("开启通知")
            }
        }
        .frame(height: 50)
        .onChange(of: switchState) { newValue in
            if switchState {
	            // 请求通知权限
	            NotificationManager.shared.requestAuthorization()

                // 调度通知 - 60秒后发送本地通知
                NotificationManager.shared.scheduleNotification()
	        }
        }
        .alert(isPresented: $notificationManager.showingAlert) {
            Alert(
                title: Text("Notification Permission"),
                message: Text("Notifications are currently disabled. Would you like to open settings to enable them?"),
                primaryButton: .default(Text("Open Settings")) {
                    if let url = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(url) {
                        UIApplication.shared.open(url)
                    }
                },
                secondaryButton: .cancel()
            )
        }
    }

}

示意图:

[SwiftUI]本地通知_第1张图片

[SwiftUI]本地通知_第2张图片

[SwiftUI]本地通知_第3张图片

你可能感兴趣的:(SwiftUI,swiftui,本地推送)