【发布时间】:2015-12-16 11:21:49
【问题描述】:
当我使用 filePath 作为字符串时,我在 Swift 1.2 中表现出色。现在 Swift 2 希望我们都使用 URL 路径,即使我正在阅读他们的文档,我也无法让它工作。
我有;
var fileName = "myRespondusCSV.csv"
let fileManager = NSFileManager.defaultManager()
let documentsURL = fileManager.URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask)
if let documentPath: NSURL = documentsURL.first as NSURL! {
filePath = documentPath.URLByAppendingPathComponent(fileName)
print(filePath)
} else {
fileManager.createFileAtPath(filePath!.path!,
contents: ("" as String).dataUsingEncoding(NSUTF8StringEncoding)!,
attributes:nil)
print("file has been created")
}
}
func excludeFileFromBackup() {
var error:NSError?
//var fileToExcludeh = NSURL.fileReferenceURL(filePath!)
var fileToExcludeh = fileURLWithPath(filePath)
let success = fileToExcludeh.setResourceValue(true, forKey: NSURLIsExcludedFromBackupKey, error: &error)
}
我收到“使用未解析的标识符“fileURLWithPath”!
我应该使用绝对 URL 路径吗?
【问题讨论】:
-
fileURLWithPath 不是(全局)函数,而是 NSURL 的方法。 SO如何使用该方法的示例有很多,最近的一个是stackoverflow.com/questions/32665508/…。
-
注释代码`//var fileToExcludeh = NSURL.fileReferenceURL(filePath!)` 似乎是正确的,那你为什么要评论呢?
-
这里的示例stackoverflow.com/questions/32665508 cannot-invoke-initializer-for-type-nsurl-with-an-argument-list-of-type-fileudoes 没有(到目前为止)有答案。 Swift 2 删除了 stringByAppendingPathComponent,这意味着我需要将路径创建为 URL。回答 Midhun MP;注释代码抛出另一个错误'函数值被用作属性;添加()来调用'。在我的代码“fileToExcludeh”中没有具有此名称的函数。