Sound/播放提示音, Haptics/触觉反馈, LocalNotification/本地通知 的使用

1. Sound 播放提示音

  1.1 音频文件:  tada.mp3, badum.mp3

  1.2 文件位置截图:

Sound/播放提示音, Haptics/触觉反馈, LocalNotification/本地通知 的使用_第1张图片

  1.3 实现

import AVKit

/// 音频管理器
class SoundManager{
    // 单例对象 Singleton
    static let instance = SoundManager()
    // 音频播放
    var player: AVAudioPlayer?
    
    enum SoundOption: String{
        case tada
        case badum
    }
    
    func playSound(sound: SoundOption){
        // 获取 url
        guard let url =  Bundle.main.url(forResource: sound.rawValue, withExtension: ".mp3") else { return }
        do{
            player = try AVAudioPlayer(contentsOf: url)
            player?.play()
        }catch let error{
            // 打印错误
            print("Error playing sound. \(error.localizedDescription)")
        }
        
    }
}

/// 提示音
struct SoundsBootcamp: View {
    var soundManager = SoundManager()
    
    var body: some View {
        
        VStack(spacing: 40) {
            Button("Play sound 1") {
                SoundManager.instance.playSound(sound: .tada)
            }
            
            Button("Play sound 2") {
                SoundManager.instance.playSound(sound: .badum)
            }
        }
    }
}

2. Haptics 触觉反馈与通知

  2.1 实现

/// 触觉管理器
class HapticManager{
    static let instance = HapticManager()
    
    // 通知
    func notification(type: UINotificationFeedbackGenerator.FeedbackType){
        let generator = UINotificationFeedbackGenerator()
        generator.notificationOccurred(type)
    }
    
    func impact(style: UIImpactFeedbackGenerator.FeedbackStyle){
        // 反馈生成器
        let generator = UIImpactFeedbackGenerator(style: style)
        generator.impactOccurred()
    }
}

/// 触觉反馈与通知
struct HapticsBootcamp: View {
    var body: some View {
        VStack(spacing: 20) {
            Button("Success") { HapticManager.instance.notification(type: .success) }
            Button("Warning") { HapticManager.instance.notification(type: .warning) }
            Button("Error") { HapticManager.instance.notification(type: .error) }
            Divider()
            Button("Soft") { HapticManager.instance.impact(style: .soft) }
            Button("Light") { HapticManager.instance.impact(style: .light) }
            Button("Medium") { HapticManager.instance.impact(style: .medium) }
            Button("Rigid") { HapticManager.instance.impact(style: .rigid) }
            Button("Heavy") { HapticManager.instance.impact(style: .heavy) }
        }
    }
}

3. LocalNotification 本地通知

  3.1 实现

import UserNotifications
import CoreLocation

/// 通知管理类
class NotificationManager{
    // 单例
    static let instance = NotificationManager() // Singleton
    
    // 请求权限
    func requestAuthorization(){
        //
        let options: UNAuthorizationOptions = [.alert, .sound, .badge]
        UNUserNotificationCenter.current().requestAuthorization(options: options) { success, error in
            if let error = error {
                print("ERROR:\(error)")
            }else{
                print("Success:\(success)")
            }
        }
    }
    
    /// 加入一个通知
    func scheduleNotification(){
        let content = UNMutableNotificationContent()
        content.title = "This is my first notification!"
        content.subtitle = "This is was so easy!"
        content.sound = .default
        content.badge = 1
        
        // time 计时器通知
         let trigger = timeNotification()
        
        // calendar 日历通知
        // let trigger = calendarNotification()
        
        // location 位置通知
        //let trigger = locationNotificationTrigger()
   
        // 通知请求
        let request = UNNotificationRequest(
            identifier: UUID().uuidString,
            content: content,
            // 触发器
            trigger: trigger)
        // 当前通知中心,添加一个通知
        UNUserNotificationCenter.current().add(request)
    }

    /// 取消通知
    func cancelNotification(){
        UNUserNotificationCenter.current().removeAllPendingNotificationRequests()
        UNUserNotificationCenter.current().removeAllDeliveredNotifications()
    }
    
    /// 位置通知
    func locationNotificationTrigger()-> UNNotificationTrigger{
        // 经纬度
        let coordinates = CLLocationCoordinate2D(
            latitude: 40.00,
            longitude: 50.00)
        // 区域 radius: 半径,以米为单位
        let region = CLCircularRegion(
            center: coordinates,
            radius: 100,
            identifier: UUID().uuidString)
        region.notifyOnEntry = true; // 进入
        region.notifyOnExit = true;  // 退出
        return UNLocationNotificationTrigger(region: region, repeats: true)
    }
    
    /// 日历通知
    func calendarNotification() -> UNNotificationTrigger{
        // calendar
        var dateComponents = DateComponents()
        dateComponents.hour = 16
        dateComponents.minute = 52
        dateComponents.weekday = 2 // 2: 星期一
        // repeats 是否重复
        return UNCalendarNotificationTrigger(dateMatching: dateComponents, repeats: true)
    }
    
    /// 计时器通知 repeats 循环/重复
    func timeNotification() -> UNNotificationTrigger{
        return UNTimeIntervalNotificationTrigger(timeInterval: 5.0, repeats: false);
    }
}

/// 本地通知
struct LocalNotificationBootcamp: View {
    var body: some View {
        VStack(spacing: 40) {
            // 获取权限
            Button("Request permission") {
                NotificationManager.instance.requestAuthorization()
            }
            Button("Schedule notification") {
                NotificationManager.instance.scheduleNotification()
            }
            Button("Cancel notification") {
                NotificationManager.instance.cancelNotification()
            }
        }
        .onAppear {
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
    }
}

  3.2 效果图:

Sound/播放提示音, Haptics/触觉反馈, LocalNotification/本地通知 的使用_第2张图片      

你可能感兴趣的:(SwiftUI,Continued,Learning,iOS,Swift,UI)