You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Swift中为FCM通知添加默认提示音?

为iOS FCM推送添加默认提示音的修改方法

要让iOS设备收到推送时播放系统默认提示音,只需在FCM请求的notification参数字典中添加"sound": "default"字段即可。

修改后的完整函数代码如下:

func notify(to token: String, title: String, body: String) {
    print("sendMessageTouser()")
    let urlString = "https://fcm.googleapis.com/fcm/send"
    let url = NSURL(string: urlString)!
    let paramString: [String : Any] = [
        "to" : token,
        "notification" : [
            "title" : title,
            "body" : body,
            "sound": "default" // 添加此行启用默认提示音
        ],
        "data" : ["user" : "test_id"]
    ]
    let request = NSMutableURLRequest(url: url as URL)
    request.httpMethod = "POST"
    request.httpBody = try? JSONSerialization.data(withJSONObject:paramString, options: [.prettyPrinted])
    request.setValue("application/json", forHTTPHeaderField: "Content-Type")
    request.setValue("key=\(legacyServerKey)", forHTTPHeaderField: "Authorization")
    let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
        do {
            if let jsonData = data {
                if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: AnyObject] {
                    NSLog("Received data:\n\(jsonDataDict))")
                }
            }
        } catch let err as NSError {
            print(err.debugDescription)
        }
    }
    task.resume()
}

额外说明

  • 确保你的iOS应用已经向用户请求了包含声音的推送权限,用户授权后才能正常播放提示音
  • 如果需要使用自定义提示音,只需将"default"替换为你的音频文件名(需提前将音频文件添加到iOS项目中,支持格式包括wav、aiff、caf等)

内容的提问来源于stack exchange,提问作者Milly Alfaro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 20:48:22