首页 > 解决方案 > 将 [URL] 提取到 URL

问题描述

我正在尝试提取 Firebase 数据库 url 引用的音频文件。我创建的功能可以下载[URL]但 AVAudioPlayer 需要URL它可以在本地播放。总体目标是流式传输音频文件。我的问题是有什么方法可以将此 url 从数组中导出为常规的 url 字符串?这篇SO 帖子是我能想到的最接近我的问题但并没有真正帮助的帖子。下面是 JSON 路径的代码片段和屏幕截图。非常感谢任何帮助和指导!

func fetchAudio(asset: AVURLAsset){
    let storageRef = Storage.storage().reference() //Referencing database
    var node : Post? //References the Post model
    let remoteAudioURL = FetchAudio.shared.storageRef.reference(forURL: (node?.audioUrl)!) //Referencing the remote audio file by way of it's respective Post
    let localURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask) //Instantiate the local destination for the downloaded audio file

    remoteAudioURL.getData(maxSize: 10 * 1024 * 1024) { (data, error) in
        if let error = error {
            print (error.localizedDescription)
        } else {
            if let d = data {
                do {
                    try d.write(to: localURL) //Error: Cannot convert value of type '[URL]' to expected argument type 'URL'
                    self.player = AVAudioPlayer(contentsOf: localURL) //Error: Cannot convert value of type '[URL]' to expected argument type 'URL'
                    self.player?.play()
                } catch {
                    print(error)
                }
            }
        }
    }
}

在此处输入图像描述

标签: swiftxcodefirebase-realtime-database

解决方案


通过使用FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)

您将获得所有不是播放特定音频文件或保存它所需的 url 。

因此,您可能需要通过执行以下操作要求 FileManager 生成文件所在的 url:

      let localURL = try! FileManager.default.url(for: .documentDirectory,
                                                in: .userDomainMask,
                                                appropriateFor: nil,
                                                create: false)
                        .appendingPathComponent("yourFileName.mp3")

推荐阅读