我正在尝试使用以下代码将文件从我的包复制到 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)
}
错误域=NSCocoaErrorDomain代码=4“文件“information.png”不存在。” UserInfo={NSSourceFilePathErrorKey=/Users/macbookpro/Library/Developer/CoreSimulator/Devices/E58CA1C6-C6F1-4D72-9572-3925675E78A5/data/Containers/Bundle/Application/EFA83E02-5F24-4BB3-B32A-7E755081A730/AutoLayout 嗯。应用程序/information.png, NSUserStringVariant=(
复制
),NSDestinationFilePath=文件:///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 {错误域=NSPOSIXErrorDomain代码=2“没有这样的文件或目录”}}
根据fileManager.fileExistsAtPath()
该文件确实存在。我究竟做错了什么?
问题是这一行:
let fullDestPathString = String(fullDestPath)
它应该是:
let fullDestPathString = fullDestPath.path
看看错误。问题是目的地。注意file:///
。您的代码未正确将 URL 转换为文件路径。您需要使用path
的财产NSURL
获取字符串形式的路径。
在所有的调试和检查中,您从未验证过fullDestPathString
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)