Swift 将包作为文件写入

Swift 将包作为文件写入,swift,Swift,我想将拖拽到项目文件夹中的包写入临时文件 以前我使用fileManager.copyItem,但它删除了原始文件 原始代码 func copycpackagedbundletodocuments(withDestinationName dest:String){ 如果let bundlePath=Bundle.main.path(forResource:embeddedBundle,of type:nil){ 让fileManager=fileManager.default 让destPath=

我想将拖拽到项目文件夹中的包写入临时文件

以前我使用fileManager.copyItem,但它删除了原始文件

原始代码

func copycpackagedbundletodocuments(withDestinationName dest:String){
如果let bundlePath=Bundle.main.path(forResource:embeddedBundle,of type:nil){
让fileManager=fileManager.default
让destPath=NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory、.userDomainMask,true)。首先!
//默认情况下,applicationSupportDirectory不是在沙盒中创建的,因此我们需要确保它存在!
让URL=fileManager.URL(用于:.applicationSupportDirectory,位于:.userDomainMask中)
如果让应用程序支持URL=URL.last{
做{
尝试fileManager.createDirectory(位于:applicationSupportURL,中间目录:true,属性:nil)
}抓住{
打印(错误)
}
}
让fullDestPath=NSURL(fileURLWithPath:destPath+“/”+dest)
做{
尝试fileManager.copyItem(atPath:bundlePath,toPath:fullDestPath.path!)
}抓住{
打印(错误)
}
}
}
这告诉我路径等都很好,因为它确实复制了文件

现在我想要一个原子拷贝,所以我想使用数据(contentsOfFile)

所以我重写了所有内容:

func copycpackagedbundletodocuments(withDestinationName dest:String){
如果let bundlePath=Bundle.main.path(forResource:embeddedBundle,of type:nil){
让fileManager=fileManager.default
让destPath=NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory、.userDomainMask,true)。首先!
//默认情况下,applicationSupportDirectory不是在沙盒中创建的,因此我们需要确保它存在!
让URL=fileManager.URL(用于:.applicationSupportDirectory,位于:.userDomainMask中)
如果让应用程序支持URL=URL.last{
做{
尝试fileManager.createDirectory(位于:applicationSupportURL,中间目录:true,属性:nil)
}抓住{
打印(错误)
}
}
设urlPath=URL(fileURLWithPath:destPath+“/”+dest)
让dta=try?数据(contentsOf:URL(fileURLWithPath:bundlePath))
做{
尝试dta.write(到:urlPath,选项:。原子)
}抓住{
打印(“错误\(错误)”)
}
}
}
然而,这里的数据(dta)为零

我认为这是因为我的包位置(如下所示)以反斜杠结尾/:

file:///Users/user/Library/Developer/CoreSimulator/Devices/37A85B0B-F2B7-4A0C-BAA7-E05A831FFAE0/data/Containers/Bundle/Application/AD665103-E256-4F6C-8248-B62D8FF9FDC8/LocalBundle.app/Bundle.bundle/

我猜copyItem可以将捆绑包视为单个文件,但是将捆绑包写入数据是不可能的(路径是正确的,因为使用copyItem的代码可以工作)

为清楚起见,请参见以下内容

    if let bundleURL = Bundle.main.url(forResource: embeddedBundle, withExtension: nil) {
        print ( try? Data(contentsOf: bundleURL ) )
    }
将nil打印到控制台,验证捆绑包的url


如何以原子方式将包写入文件?

moveItem
删除源位置的项,
copyItem
不删除。您是否阅读了我对您的一个问题(如何处理应用程序支持文件夹)的回答?。这避免了检查和显式创建目录。强烈建议始终使用
Bundle
FileManager
中与URL相关的API。在Swift中不要使用
NSURL
。这是有道理的,但重写的版本不使用NSURL,即使没有显式创建目录,也会显示nil作为数据。因此,我不清楚如何从这里开始…重写的版本没有附加文件名(无论如何,
urlPath
是什么?),这是至关重要的。我的意思是NSData不是NSURLPATH有点不相关,它是目标路径,但由于数据(对于数据或NData也是一样)为零…在任何情况下,我已经更新了问题以使用数据。我现在使用的是应用程序支持文件夹的显式检查,这是一个完全不同的问题。