[英]NSFileManager fileExistsAtPath unable to overwrite existing file in Swift 2
您好,我正在将现有代码升级到Swift 2,我需要一些有关DocumentDirectoy中文件副本的帮助。
这是我用来检查文件是否存在的转换后的代码,如果存在,我们应该以任何一种方式对其进行复制,但是它始终返回一个错误,指出该文件存在,这是真的,但是我们需要覆盖它。
func copyXMLFile()
{
// Get a reference for the Document directory
let rootPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, .UserDomainMask, true)[0]
// Get a reference for the data.xml file
xmlPathInDocument = rootPath.stringByAppendingString("data.xml")
if NSFileManager.defaultManager().fileExistsAtPath(xmlPathInDocument){
print("xml file exists")
let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
do {
// copy file from main bundle to documents directory
print("copy")
try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
} catch let error as NSError {
// Catch fires here, with an NSErrro being thrown
print("error occurred, here are the details:\n \(error)")
}
}
else
{
// copy the file either way
let xmlPathInBundle = NSBundle.mainBundle().pathForResource("data", ofType: "xml")!
do {
// copy file from main bundle to documents directory
print("copy")
try NSFileManager.defaultManager().copyItemAtPath(xmlPathInBundle, toPath: xmlPathInDocument)
} catch let error as NSError {
// Catch fires here, with an NSErrro being thrown
print("error occurred, here are the details:\n \(error)")
}
}
}
发生错误,以下是详细信息:
错误域= NSCocoaErrorDomain代码= 516“无法完成操作。(可可错误516。)” UserInfo = 0x7a67b680 {NSSourceFilePathErrorKey = / Users / User1 / Library / Developer / CoreSimulator / Devices / 0E591E5B-2E2F-4CCB-9099- 95CE1EA3F557 / data / Containers / Bundle / Application / E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE / myApp.app / data.xml,NSUserStringVariant =(Copy),NSFilePath = / Users / User1 / User1 / Library / Developer / CoreSimulator / Devices / 0E591E5 -2E2F-4CCB-9099-95CE1EA3F557 /数据/容器/捆绑/应用程序/E3C8FAE4-703D-46CA-AC37-A1C96A74E6BE/myApp.app/data.xml,NSDestinationFilePath=/用户/用户1 /用户1 /库/开发人员/ CoreSimulator /设备/ 0E591E5B-2E2F-4CCB-9099-95CE1EA3F557 /数据/容器/数据/应用程序/09F690B3-BDD8-4482-ADDE-E33F30D4B873/Documentsdata.xml,NSUnderlyingError=0x7a67dd80“操作无法完成。文件存在”}
请帮忙!
实现NSFileManagerDelegate
和委托方法
optional func fileManager(_ fileManager: NSFileManager,
shouldProceedAfterError error: NSError,
copyingItemAtURL srcURL: NSURL,
toURL dstURL: NSURL) -> Bool
并返回true
或者,您可以使用
func replaceItemAtURL(_ originalItemURL: NSURL,
withItemAtURL newItemURL: NSURL,
backupItemName backupItemName: String?,
options options: NSFileManagerItemReplacementOptions,
resultingItemURL resultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.