iOS 中的 FCM 通知在收到时不会播放声音

ios

1个回答

写回答

咖咖i

2025-06-21 12:25

+ 关注

IOS
IOS

IOS 中的 FCM 通知在收到时不会播放声音

自然语言生成文章:

FCM(Firebase Cloud Messaging)是一种用于发送推送通知的解决方案,广泛应用于移动应用程序开发中。然而,一些开发者可能会遇到一个问题:在 IOS 设备上收到 FCM 通知时,通知并不会播放声音。本文将介绍这个问题的原因,并提供解决方案。

IOS 设备上,通知的声音播放是由设备的操作系统控制的。IOS 设备上的通知声音由两个主要因素决定:推送通知的声音设置和应用程序的通知设置。如果用户在设置中将推送通知的声音关闭,那么即使 FCM 通知设置了声音,设备也不会播放声音。此外,如果应用程序的通知设置中将声音关闭,即使推送通知的声音设置为开启,设备也不会播放声音。

解决这个问题的方法是在应用程序的代码中设置通知的声音。为了实现这一点,我们需要在发送 FCM 通知时指定一个特定的声音文件,并在应用程序代码中添加相应的逻辑来处理该声音文件。

首先,我们需要在应用程序的资源文件中添加一个声音文件,例如名为 "notification_sound.mp3" 的文件。然后,我们需要在发送 FCM 通知时指定这个声音文件。下面是一个使用 Firebase Admin SDK 发送 FCM 通知的示例代码:

Python

from firebase_admin import messaging

def send_notification():

message = messaging.Message(

notification=messaging.Notification(

title='New Notification',

body='You have a new notification',

sound='notification_sound.mp3'

),

token='DEVICE_TOKEN'

)

response = messaging.send(message)

print('Successfully sent message:', response)

在上面的示例代码中,我们使用 Firebase Admin SDK 发送一个带有标题、正文和声音的 FCM 通知。请注意,在 sound 字段中指定了声音文件的名称。

接下来,我们需要在应用程序的代码中处理这个声音文件。在 IOS 的应用程序代码中,我们可以使用 UNNotificationSound 类来指定通知的声音。下面是一个示例代码:

Swift

import UserNotifications

func registerForPushNotifications() {

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge]) { (granted, error) in

if granted {

DispatchQueue.mAIn.async {

UIApplication.shared.registerForRemoteNotifications()

}

}

}

}

extension AppDelegate: UNUserNotificationCenterDelegate {

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

completionHandler([.alert, .sound, .badge])

playCustomSound()

}

func playCustomSound() {

guard let url = Bundle.mAIn.url(forResource: "notification_sound", withExtension: "mp3") else { return }

var sound: SystemSoundID = 0

AudIOServicesCreateSystemSoundID(url as CFURL, &sound)

AudIOServicesPlaySystemSound(sound)

}

}

在上面的示例代码中,我们首先调用 registerForPushNotifications 函数来请求用户授权推送通知,并在用户授权后注册远程通知。然后,我们扩展了 AppDelegate,实现了 UNUserNotificationCenterDelegate 协议中的两个方法:userNotificationCenter(_:willPresent:withCompletionHandler:)playCustomSound。在 userNotificationCenter(_:willPresent:withCompletionHandler:) 方法中,我们指定了通知的显示选项,并调用 playCustomSound 方法来播放自定义声音。

通过在应用程序的代码中指定通知的声音,我们可以确保在收到 FCM 通知时播放声音。这样,用户就能够直观地感知到新的通知,并及时采取相应的行动。

IOS 设备上收到 FCM 通知时不会播放声音的问题可以通过在应用程序的代码中指定通知的声音来解决。通过添加相应的逻辑来处理自定义声音文件,我们可以确保在收到 FCM 通知时播放声音,提升用户体验。以上是解决这个问题的简单示例代码,开发者可以根据自己的需求进行相应的修改和扩展。希望本文能帮助到遇到这个问题的开发者们。

举报有用(4分享收藏

Copyright © 2025 IZhiDa.com All Rights Reserved.

知答 版权所有 粤ICP备2023042255号