我基本上试图将音频文件保存到 iPhone 设备,特别是在“文件”应用程序中。

这是我正在使用的在 iOS 模拟器中运行的代码:

if let audioUrl = URL(string: "https://file-examples.com/wp-content/uploads/2017/11/file_example_MP3_700KB.mp3") {

    // then lets create your document folder url
    let documentsDirectoryURL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!

    // lets create your destination file url
    let destinationUrl = documentsDirectoryURL.appendingPathComponent(audioUrl.lastPathComponent)
    print(destinationUrl)

    // to check if it exists before downloading it
    if FileManager.default.fileExists(atPath: destinationUrl.path) {
        print("The file already exists at path", destinationUrl)

        // if the file doesn't exist
    } else {

        // you can use NSURLSession.sharedSession to download the data asynchronously
        URLSession.shared.downloadTask(with: audioUrl) { location, response, error in
            guard let location = location, error == nil else { return }
            do {
                // after downloading your file you need to move it to your destination url
                try FileManager.default.moveItem(at: location, to: destinationUrl)
                print("File moved to documents folder", destinationUrl)
            } catch {
                print(error)
            }
        }.resume()
    }
}

这是模拟器中的结果:

2022-04-08 15:48:17.605964+0200 TunnelPlay[3977:122650] [boringssl] boringssl_metrics_log_metric_block_invoke(153) Failed to log metrics

File moved to documents folder file:///Users/panashemuzamhindo/Library/Developer/CoreSimulator/Devices/A7F7DD88-1E0C-45CD-9783-F46E6644F98C/data/Containers/Data/Application/EDE8B3CC-C290-4369-8B88-4AE1717B9DB8/Documents/1645329769Sengkhathele(featit.caramel).mp3

主要问题:当我尝试在 TestFlight 中运行此部分时,应用程序运行保存过程,但文件中没有任何内容,也许我在错误的位置寻找它?或者我需要一些权限?

期望的结果:我想在 iPhone 文件应用程序中查看下载的 MP3。

我确实尝试将方案更改为“发布”而不是“调试”,但它仍然不保存文件。


如果您希望能够访问 iOS 文件应用程序中的文件,请确保还启用LSSupportsOpeningDocumentsInPlace(除了启用 之外UIFileSharingEnabled

LSSupportsOpeningDocumentsInPlace 一个布尔值,指示应用程序是否可以从文件提供程序打开原始文档,而不是文档的副本。

UIFileSharingEnabled 一个布尔值,指示应用程序是否共享文件。


崩溃原因消息?崩溃的线程堆栈跟踪?

@PhillipMills 好的,现在它没有崩溃,我不确定为什么应用程序运行顺利,该应用程序只是运行脚本,但当我检查文件时没有任何内容

@PhillipMills 也许我在错误的位置寻找它???或者我需要权限??,因为现在没有崩溃,所以没有崩溃的线程堆栈跟踪

@PhillipMills 发现了如果您希望能够访问 iOS 文件应用程序中的文件,请确保还启用 LSSupportsOpeningDocumentsInPlace (除了启用 UIFileSharingEnabled 之外)。