每次启动/重新运行应用程序时,iOS 文件路径都会发生变化

标签 ios swift file-manager

我在每次启动应用程序时更改文件路径时遇到问题。 我在应用程序包中有一个文件(“AppConstant.json”),我需要将该文件复制到应用程序文档目录中。我成功地将“AppConstant.json”文件保存在文档目录中创建的用户文件夹“MyFolder”中。

但问题是当我第二次重新启动应用程序时,它没有显示相同的路径。我也使用相对路径,但仍然没有得到。

这是代码 //调用目录

let stringAppConstant = copyFileFromBundleToDocumentDirectory(resourceFile: "AppConstant", resourceExtension: "json")

//保存或获取退出文件路径

func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) -> String 
  {
        var stringURLPath = "Error_URLPath"
        let fileManager = FileManager.default
        let docURL = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
        let fileName = "\(resourceFile).\(resourceExtension)"
        guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
            return stringURLPath
        }

       if !fileManager.fileExists(atPath: newDestPath.path) {
            do {
                try fileManager.createDirectory(atPath: newDestPath.path,withIntermediateDirectories: true, attributes: nil)
                print("Created folder successfully in :::", newDestPath.path)
            } catch {
                print("Error in creating folder :::",error.localizedDescription);
            }
        }
        else {
            print("Folder is already exist!")
        }
        if fileManager.fileExists(atPath: fullDestPath.path) {
            print("File is exist in ::: \(fullDestPath.path)")
            stringURLPath = fullDestPath.path
        }
        else {
            do {
                try fileManager.copyItem(atPath:  sourcePath, toPath: fullDestPath.path)
                print("Saved file successfully in :::", fullDestPath.path)
                stringURLPath = fullDestPath.path
            } catch {
                print("Error in creating file ::: \(error.localizedDescription)")
            }
        }
        return stringURLPath
    }

请帮助我,我需要在沙盒中保存路径。这是我实现的正确方法吗?

我在设备和模拟器中运行,重新启动时两个路径不同 这是第一次启动的路径: /var/mobile/Containers/Data/Application/81B568A7-0932-4C3E-91EB-9DD62416DFE8/Documents/MyFolder/AppConstant.json

重新启动应用程序我得到新路径: /var/mobile/Containers/Data/Application/3DAABAC3-0DF5-415B-82A5-72B204311904/Documents/MyFolder/AppConstant.json

注意:我创建了一个示例项目,并使用相同的代码并且它正在工作。但在现有项目中它不起作用。我仅对示例和项目使用相同的包 ID 和配置文件。检查添加的文件引用、设置、版本是否都相同。

有什么想法吗?

最佳答案

容器路径周期性变化的行为是正常的。

这些行

let destFolderPath = URL(string:docURL)?.appendingPathComponent("MyFolder")
let fileName = "\(resourceFile).\(resourceExtension)"
guard let newDestPath = destFolderPath, let sourcePath = Bundle.main.path(forResource: resourceFile, ofType: ".\(resourceExtension)"), let fullDestPath = NSURL(fileURLWithPath: newDestPath.absoluteString).appendingPathComponent(fileName) else {
    return stringURLPath
}

错误较多

  • URL(string 是错误的文件路径 API,它是 URL(fileURLWithPath)
  • path(forResource:ofType:) 的第二个参数不得有前导点。
  • API absoluteString 作为 URL(fileURLWithPath) 的参数是错误的
  • 这不是真正的错误,但不要在 Swift 中使用 NSURL

强烈建议始终使用 URL 相关 API 来连接路径并从 FileManager 获取文档文件夹。此外,最好的做法是让方法抛出真正的错误,而不是返回无意义的文字字符串。并且 NSSearchPathForDirectoriesInDomains 已过时,不应在 Swift 中使用。

func copyFileFromBundleToDocumentDirectory(resourceFile: String, resourceExtension: String) throws -> URL
{
    let sourceURL = Bundle.main.url(forResource: resourceFile, withExtension: resourceExtension)!
    
    let fileManager = FileManager.default
    let destFolderURL = try fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: false).appendingPathComponent("MyFolder")
    let fullDestURL = destFolderURL.appendingPathComponent(resourceFile).appendingPathExtension(resourceExtension)
    
    if !fileManager.fileExists(atPath: destFolderURL.path) {
        try fileManager.createDirectory(at: destFolderURL, withIntermediateDirectories: true, attributes: nil)
        print("Created folder successfully in :::", destFolderURL.path)
        try fileManager.copyItem(at: sourceURL, to: fullDestURL)
        print("Saved file successfully in :::", fullDestURL.path)
    } else {
        print("Folder already exists!")
        if fileManager.fileExists(atPath: fullDestURL.path) {
            print("File exists in ::: \(fullDestURL.path)")
        } else {
            try fileManager.copyItem(at: sourceURL, to: fullDestURL)
            print("Saved file successfully in :::", fullDestURL.path)
        }
    }
    return fullDestURL
}

关于每次启动/重新运行应用程序时,iOS 文件路径都会发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63423828/

相关文章:

ios - 使用 Facebook 为 iOS 设置 Firebase 简单登录

android - 使用 URL 方案的 Google Pay UPI 集成 - iOS

ios - 从 AppDelegate 调用 ViewController 的成员函数

ios - 使用 NSUserDefaults 在 Swift 中保存和加载高分

ios - 音乐程序的 TabBarController

ios - 根据与特定属性相对应的另一个数组中的值对对象数组进行排序

ios - 如何在文件管理器中快速读取json文件?

ANDROID - Intent 将应用程序作为文件管理器启动

ios - 解析从 Int 到 String 的转换不起作用

jquery - 蒂姆塞 4 : how to create your own file manager?