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

Swift中从文档目录选中音频文件后如何打开指定ViewController

iOS 文档选择器选中音频后跳转指定ViewController修复方案

你的代码主要存在4个可调整的点,修改后即可正常实现需求:

  • 旧版UIDocumentPicker代理方法已经在iOS 11后被废弃,系统不会触发回调
  • .import模式返回的URL是临时文件路径,会被系统自动回收,直接传给下一页可能出现无法读取的问题
  • 跳转前需要先关闭文档选择器弹窗,避免跳转逻辑被拦截
  • 若当前页面没有嵌套在UINavigationController中,push操作会直接失效

修改后的完整代码

1. 调起文档选择器的代码(原有代码仅需补充协议声明即可)

首先确保当前ViewController遵守UIDocumentPickerDelegate协议:

class YourViewController: UIViewController, UIDocumentPickerDelegate {
    // 原有其他代码
    @IBAction func startBtn(_ sender: UIButton) {
        let pickerController = UIDocumentPickerViewController(documentTypes: ["public.audio"], in: .import)
        pickerController.delegate = self
        pickerController.modalPresentationStyle = .fullScreen
        self.present(pickerController, animated: true)
    }
}

2. 替换旧的代理回调方法

// 新版系统回调方法,iOS 11+支持
func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
    guard let selectedAudioURL = urls.first else { return }
    // 将临时文件拷贝到沙盒,避免被系统回收
    let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let targetURL = docDir.appendingPathComponent(selectedAudioURL.lastPathComponent)
    do {
        if FileManager.default.fileExists(atPath: targetURL.path) {
            try FileManager.default.removeItem(at: targetURL)
        }
        try FileManager.default.copyItem(at: selectedAudioURL, to: targetURL)
        // 实例化目标VC,改用可选绑定避免强转崩溃
        guard let playVC = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PlaySoundsViewController") as? PlaySoundsViewController else {
            controller.dismiss(animated: true)
            return
        }
        playVC.recordedAudioURL = targetURL
        // 先关闭选择器再执行跳转
        controller.dismiss(animated: true) { [weak self] in
            // 有导航栏就push,没有就present,二选一即可
            if let nav = self?.navigationController {
                nav.pushViewController(playVC, animated: true)
            } else {
                playVC.modalPresentationStyle = .fullScreen
                self?.present(playVC, animated: true)
            }
        }
    } catch {
        print("文件保存失败:\(error)")
        controller.dismiss(animated: true)
    }
}

// 可选:实现取消选择的回调
func documentPickerWasCancelled(_ controller: UIDocumentPickerViewController) {
    controller.dismiss(animated: true)
}

额外检查项

  • 确认Main.storyboard中PlaySoundsViewController的Storyboard ID确实设置为PlaySoundsViewController,且Custom Class已经绑定为对应的类
  • 如果需要限制选择的音频格式,可以替换public.audio为具体的UTI,比如public.mp3、com.microsoft.waveform-audio等

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 15:06:00