【问题标题】:Send Haptics with Custom Sound on Local Notification在本地通知上发送带有自定义声音的触觉
【发布时间】:2019-11-29 16:19:08
【问题描述】:

我有一个应用程序,我会在指定时间发送通知以帮助用户记住事情。在通知中实现自定义声音时遇到问题。当手机的铃声打开时,我会播放声音,但是我想让它在发送时播放触觉反馈。无论铃声是否打开,iOS 默认声音都会在传递时播放触觉。

我的代码如下所示:

var sounds = ["default", "definite", "quite-impressed", "rush", "serious-strike", "what-friends-are-for"]
var sound = 0
let soundNumber = defaults.integer(forKey: "alarmSound")

let notificationContent = UNMutableNotificationContent()
notificationContent.title = defaults.string(forKey: "notificationBody") ?? "Time to eat!"
notificationContent.body = defaults.string(forKey: "notificationText") ?? "Your timers have gone off!"

if sound == 0 {
    notificationContent.sound = UNNotificationSound.default
} else {
    notificationContent.sound = UNNotificationSound.init(named: UNNotificationSoundName(rawValue: "\(sounds[sound]).m4a"))
}

notificationContent.categoryIdentifier = NotificationActions.Category.snooze

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: differenceInDates, repeats: false)
let request = UNNotificationRequest(identifier: "\(i)", content: notificationContent, trigger: trigger)

UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

sounds 数组是声音文件名的数组,它从 UserDefaults 中获取声音的索引并使用该文件设置通知声音。

感谢任何帮助!

【问题讨论】:

    标签: ios notifications uilocalnotification


    【解决方案1】:

    实现UNUserNotificationCenterDelegateuserNotificationCenter(_center:willPresent:withCompletionHandler) 您可以通过两种方式为通知传递没有声音效果并播放自己的声音。

    忽略设备中的静音模式

    var sound: SystemSoundID = 0
    AudioServicesCreateSystemSoundID(url as CFURL, &sound)
    AudioServicesPlaySystemSound(sound)
    

    或仅在静音模式关闭时

    let audioPlayer = try? AVAudioPlayer(contentsOf: url)
    audioPlayer?.prepareToPlay()
    audioPlayer?.volume = 1.0
    audioPlayer?.play()
    

    AppDelegate 文件中的设置

    import UserNotifications
    .......
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        UNUserNotificationCenter.current().delegate = self
        return true
    }
    .......
    extension AppDelegate: UNUserNotificationCenterDelegate {
    
        func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.badge, .alert])
            // play sound here
        }
    }
    

    但它仅在应用程序处于前台时才有效。我认为您无法为警报发送触觉和振动效果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-02
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2019-09-14
      • 2014-04-15
      相关资源
      最近更新 更多