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

iOS/Xcode实现音频文件直接分享至WhatsApp(跳过系统分享菜单)

直接打开WhatsApp分享iOS音频文件的解决方案

你想绕过系统分享菜单直接跳转到WhatsApp分享音频的需求完全可以实现,我给你调整代码并解释清楚逻辑:

首先先优化你现有代码里的一些Swift写法(比如替换NSData为原生Data,更符合现代Swift规范),然后重点实现直接唤起WhatsApp的逻辑:

方法1:使用UIDocumentInteractionController(推荐)

这个方法可以直接唤起WhatsApp的文件分享界面,让用户选择联系人,完全跳过系统分享菜单。

修改后的完整代码如下:

// 获取原始文件
let fileName = #MY FILE NAME#
guard let filePath = Bundle.main.path(forResource: fileName, ofType: "mp3"),
      let fileData = try? Data(contentsOf: URL(fileURLWithPath: filePath)) else {
    print("无法读取音频文件")
    return
}

// 创建可访问的临时分享文件
let newFileName = "file.mp3"
guard let documentsDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else {
    print("无法获取Documents目录")
    return
}
let newFileURL = documentsDir.appendingPathComponent(newFileName)

do {
    try fileData.write(to: newFileURL)
} catch {
    print("写入临时文件失败: \(error.localizedDescription)")
    return
}

// 直接唤起WhatsApp分享
let documentInteractionController = UIDocumentInteractionController(url: newFileURL)
// 指定WhatsApp的UTI,确保直接打开它
documentInteractionController.uti = "net.whatsapp.audio"
// 设置代理(需要当前ViewController遵守UIDocumentInteractionControllerDelegate)
documentInteractionController.delegate = self
// 弹出WhatsApp的分享界面
documentInteractionController.presentOpenInMenu(from: view.bounds, in: view, animated: true)

注意事项:

  • 你需要让当前的ViewController遵守UIDocumentInteractionControllerDelegate协议,至少实现一个基础代理方法,示例:
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController? {
        return self
    }
    
  • net.whatsapp.audio是WhatsApp官方认可的音频文件UTI,能确保系统直接唤起WhatsApp而非弹出系统菜单

方法2:使用WhatsApp URL Scheme(适合分享到特定联系人)

如果你想直接分享给某个已知的WhatsApp联系人,可以用URL Scheme,但需要提前知道联系人的手机号(带国际区号):

// 假设你已经生成了newFileURL(和上面的文件生成步骤一致)
// 替换成目标联系人的手机号,比如+1234567890
let phoneNumber = "+1234567890"
if let whatsAppURL = URL(string: "whatsapp://send?phone=\(phoneNumber)&audio=\(newFileURL.absoluteString)") {
    if UIApplication.shared.canOpenURL(whatsAppURL) {
        UIApplication.shared.open(whatsAppURL, options: [:], completionHandler: nil)
    } else {
        print("未安装WhatsApp")
    }
}

额外配置:

别忘了在Info.plist里添加允许查询WhatsApp URL Scheme的配置,否则会无法唤起:

<key>LSApplicationQueriesSchemes</key>
<array>
    <string>whatsapp</string>
</array>

这样就能完全绕过系统分享菜单,直接打开WhatsApp完成音频分享啦!

内容的提问来源于stack exchange,提问作者Antoine Nedelec

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:09:50