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

news/2024/7/20 22:24:19 标签: iOS, Swift, UI

1. Sound 播放提示音

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

  1.2 文件位置截图:

  1.3 实现

Swift">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 实现

Swift">/// 触觉管理器
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 实现

Swift">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 效果图:

      


http://www.niftyadmin.cn/n/5052587.html

相关文章

VBA学习方法3.2.4:VBA中的查找操作

【分享成果,随喜正能量】一旦被欲望的毒箭射中,心会变得麻木,失去觉知,甚至疯狂。如果没有及时清醒,就会如同爱美的飞蛾扑向火焰、贪吃的鱼儿被鱼钩钓起,当发现自己身处险境时,后悔也来不及了。…

TensorFlow入门(五、指定GPU运算)

一般情况下,下载的TensorFlow版本如果是GPU版本,在运行过程中TensorFlow能自动检测。如果检测到GPU,TensorFlow会默认利用找到的第一个GPU来执行操作。如果机器上有超过一个可用的GPU,除第一个之外的其他GPU默认是不参与计算的。如果想让TensorFlow使用这些GPU执行操作,需要将运…

一文详解Web自动化测试

1 什么是Selenium 专门用来测试Web应用程序的自动化测试工具。 2 搭建环境 2.1 Python 开发环境 2.2 安装selenium包 2.3 安装浏览器(最新版本谷歌/火狐)与浏览器驱动 2.2 安装selenium包:通过python解释器自带的pip工具进行安装&#…

Buildroot添加自定义文件

在日常开发中,我们经常会向buildroot文件系统里添加自定义文件。本文介绍几种添加的方法 一、buildroot/system/skeleton目录 skeleton能够在目标文件系统编译完成后将指定文件覆盖到某个目录。通过这种方式,我们可以方便地添加或修改一些文件到根文件系…

前端第二课,HTML,alt,title,width/heigh,border,<a>超链接,target,tr,td,th

目录 一、title: 💛 ​二、alt💙 三、width/heigh💜 四、border ❤️ 五、超链接💚 六、target 💗 七、tr💕 八、td💘 九、th💞 十、rowspan 一、title: 💛 快…

ChatGPT推出全新功能,引发人工智能合成声音担忧|百能云芯

人工智能AI科技企业OpenAI公司25日宣布,其聊天应用程序ChatGPT如今具备「看、听、说」能力,至少能够理解口语、用合成语音回应并且处理图像;但专家忧心,以假乱真与深度伪造的乱象可能变本加厉。 国家广播公司新闻网(NBC News)报导…

高等数学应试考点速览(上)

极限 上界存在,则上确界存在数列极限 定义性质:唯一、有界(保序、夹逼、不等式性质)、保号、四则运算判定: 单侧:单调有界双侧:闭区间套增量:柯西审敛 归并和收敛子列聚点有限覆盖原…

外汇天眼:SEC起诉“现金流之王”播客主持人涉嫌1100万美元庞氏骗局

美国证券交易委员会(SEC)今天指控了“现金流之王”播客主持人马修莫蒂尔,涉嫌通过一个庞氏骗局欺骗超过50名投资者,非法筹集了约1100万美元,涉及的票据据称由住宅物业支持。 根据SEC的投诉,俄亥俄州北奥尔姆…