ios - 无法将文件从包复制到 iOS 中的文档目录

标签 ios swift copy bundle

我正在尝试使用以下代码将文件从我的包复制到 iOS 中的文档目录。

let bundlePath = NSBundle.mainBundle().pathForResource("information", ofType: ".png")
print(bundlePath, "\n") //prints the correct path
let destPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
let fileManager = NSFileManager.defaultManager()
let fullDestPath = NSURL(fileURLWithPath: destPath).URLByAppendingPathComponent("information.png")
let fullDestPathString = String(fullDestPath)
print(fileManager.fileExistsAtPath(bundlePath!)) // prints true

do{
try fileManager.copyItemAtPath(bundlePath!, toPath: fullDestPathString)
}catch{
    print("\n")
    print(error)
}

Error Domain=NSCocoaErrorDomain Code=4 "The file “information.png” doesn’t exist." UserInfo={NSSourceFilePathErrorKey=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts.app/information.png, NSUserStringVariant=( Copy ), NSDestinationFilePath=file:///Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Data/Application/86A1BDD5-FAF2-486E-85A9-CF72A547C6CD/Documents/information.png, NSFilePath=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout tuts.app/information.png, NSUnderlyingError=0x7fb53251cd80 {Error Domain=NSPOSIXErrorDomain Code=2 "No such file or directory"}}

根据 fileManager.fileExistsAtPath() 文件确实存在。我做错了什么?

最佳答案

问题是这一行:

let fullDestPathString = String(fullDestPath)

应该是:

let fullDestPathString = fullDestPath.path

查看错误。问题是目的地。注意 file:///。您的代码没有正确地将 URL 转换为文件路径。您需要使用 NSURLpath 属性来获取字符串形式的路径。

在所有调试和检查中,您从未验证过 fullDestPathString 的值。

关于ios - 无法将文件从包复制到 iOS 中的文档目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34346220/

相关文章:

arrays - Swift - 通过修剪给定父项中的子项 "owned"来过滤数组

objective-c - 如何从单元格的内容 View 中删除 subview ?

ios - 格式化为 2 位小数 (NSDecimalNumber)

ios - 如何将两个数组合并到字典中?

arrays - 从基于另一个数组的数组中删除对象

c++ - 将堆栈的值分配给另一个堆栈

ios - CoreLocation 在一定时间后停止在后台工作

objective-c - 检查用户是否在连续的 UISlider 上完成滑动?

c - 在 C 中复制两个文件时出现垃圾?

C++ 将文件从资源复制到目录?