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

wbgh16ku  于 2023-03-05  发布在  iOS
关注(0)|答案(3)|浏览(268)

我在每次启动应用程序时更改文件路径时遇到问题。我在应用程序包中有一个文件(“AppConstant.json”),我需要将此文件复制到应用程序文档目录中。我成功地将“AppConstant.json”文件保存到文档目录中创建的用户文件夹“MyFolder”中。
但问题是当我第二次重新启动应用程序时,它没有显示相同的路径,而且我使用了relativepath,但它仍然没有得到。
下面是调用目录的代码//

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

注意:我创建了一个示例项目,使用了相同的代码,并且它可以正常工作。但在现有项目中,它无法正常工作。我仅对示例和项目使用相同的bundle id和配置文件。检查了文件,添加了引用、设置、版本,所有内容均相同。

你知道吗?

pcww981p

pcww981p1#

容器路径周期性更改的行为是正常的。
这些线

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获取文档文件夹。此外,使方法throw成为真正的错误而不是返回无意义的文字字符串是一个很好的做法。而且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
}
cwtwac6a

cwtwac6a2#

编辑1:

嗨,我创建了一个新项目,使用了我在main中发布的相同代码,它工作正常。但是在真实的项目中它不工作。
如果不确定项目中到底发生了什么,请尝试调试它。这也是开发的一部分。:)
如果您急于在本周末修复此问题,请尝试使用以下代码片段。

// collect data from bundle
let constFileURL = Bundle.main.url(forResource: "AppConst", withExtension: "json")!
let data = try! Data(contentsOf: constFileURL)

// try to write data in document directory
do {
    let constFileURL = try saveFileInDocumentDirectory(filePath: "MyFolder/AppConst.json", data: data)
    // use your `constFileURL`
} catch (let error as FileOperationError) {
    switch error {
    case .fileAlreadyExists(let url):
        let data = try! Data(contentsOf: url)
        print(String(data: data, encoding: .utf8))
    case .IOError(let error):
        print("IO Error \(error)")
    }
} catch {
    print("Unknown Error \(error)")
}

// Helpers
enum FileOperationError: Error {
    case fileAlreadyExists(url: URL)
    case IOError(Error)
}
func saveFileInDocumentDirectory(filePath: String, data: Data) throws -> URL {
    
    // final destination path
    let destURLPath = fullURLPathOf(filePath, relativeTo: .documentDirectory)
    // check for file's existance and throw error if found
    guard FileManager.default.fileExists(atPath: destURLPath.path) == false else {
        throw FileOperationError.fileAlreadyExists(url: destURLPath)
    }
    // Create Intermidiate Folders
    let intermidiateDicPath = destURLPath.deletingLastPathComponent()
    if FileManager.default.fileExists(atPath: intermidiateDicPath.path) == false {
        do {
            try FileManager.default.createDirectory(at: intermidiateDicPath, withIntermediateDirectories: true, attributes: nil)
        } catch {
            throw FileOperationError.IOError(error)
        }
    }
    
    // File Writing
    do {
        try data.write(to: destURLPath, options: .atomic)
    } catch {
        throw FileOperationError.IOError(error)
    }
    return destURLPath
}
func fullURLPathOf(_ relativePath: String, relativeTo dic:FileManager.SearchPathDirectory ) -> URL {
    return FileManager.default.urls(for: dic, in: .userDomainMask).first!.appendingPathComponent(relativePath)
}

原始答案

为什么不直接在文件操作成功时返回"MyFolder/\(fileName)"呢?如果以后需要访问路径,可以使用FileManager API。

let docDir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let constFilePath = docDir.appendingPathComponent("MyFolder/\(fileName)")

// Access const file data
do { 
  let fileData = try Data(contentsOf: constFilePath)

  // Use you data for any further checking

} catch {
  // Error in reading file data
  print("Error in file data access : \(error)")
}
lnxxn5zx

lnxxn5zx3#

这对我很有效:
由于应用程序沙盒目录每次都会更改,因此您需要获取新的应用程序目录URL并附加文件名,仅此而已!!
示例:

let newPath = (NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString).appendingPathComponent(oldUrl.lastPathComponent)
let newUrl = URL(fileURLWithPath: newPath)

其中,oldUrl. lastPathComponent是您的文件名。扩展名(例如:我的文件. mp3)
PD:在我的例子中,我没有创建子文件夹。如果你创建了子文件夹,那么你必须添加子文件夹,然后添加fileName.extension
希望这能帮上忙。

相关问题