我正在尝试将Apple的"ShapeEdit"示例转换为Swift 3,我无法理解URL
setResourceValue
的更改。< / p>
Apple(Swift 2)示例包含以下代码:
// Coordinate reading on the source path and writing on the destination path to copy.
let readIntent = NSFileAccessIntent.readingIntentWithURL(templateURL, options: [])
let writeIntent = NSFileAccessIntent.writingIntentWithURL(target, options: .ForReplacing)
NSFileCoordinator().coordinateAccessWithIntents([readIntent, writeIntent], queue: self.coordinationQueue) { error in
if error != nil { return }
do {
try fileManager.copyItemAtURL(readIntent.URL, toURL: writeIntent.URL)
try writeIntent.URL.setResourceValue(true, forKey: NSURLHasHiddenExtensionKey)
NSOperationQueue.mainQueue().addOperationWithBlock {
self.openDocumentAtURL(writeIntent.URL)
}
} catch {
fatalError("Unexpected error during trivial file operations: \(error)")
}
}
setResourceValue(value: forKey:)
似乎已被setResourceValues()
取代,但我无法设置它。到目前为止我所拥有的是:
let readIntent = NSFileAccessIntent.readingIntent(with: templateURL, options: [])
let writeIntent = NSFileAccessIntent.writingIntent(with: target, options: .forReplacing)
NSFileCoordinator().coordinate(with: [readIntent, writeIntent], queue: self.coordinationQueue) { error in
if error != nil { return }
do {
try fileManager.copyItem(at: readIntent.url, to: writeIntent.url)
var resourceValues: URLResourceValues = URLResourceValues.init()
resourceValues.hasHiddenExtension = true
// *** Error on next line ***
try writeIntent.url.setResourceValues(resourceValues)
// Cannot use mutating member on immutable value: 'url' is a get-only property
OperationQueue.main.addOperation {
self.openDocumentAtURL(writeIntent.URL)
}
} catch {
fatalError("Unexpected error during trivial file operations: \(error)")
}
}
我找不到除Xcode之外的任何文档&#34;跳转到定义&#34;,其中说
设置由给定资源键标识的资源值。
此方法将新资源值写入后备存储。尝试设置只读资源属性或设置资源不支持的资源属性将被忽略,不会被视为错误。此方法目前仅适用于文件系统资源的URL。
URLResourceValues
会跟踪已设置的属性。这些值是此函数使用的值 确定要写的属性。
public mutating func setResourceValues(_ values: URLResourceValues) throws
有没有人对setResourceValue(s)
的变化有任何了解?
答案 0 :(得分:7)
NSFileAccessIntent.URL
的当前声明是
public var url: URL { get }
它是一个只读属性。
由于Swift 3 URL
是struct
,因此您无法对从getter返回的不可变值调用变异方法。要修改网址,请先将其分配给var
。
var url = intent.URL
url.setResourceValues(...)
然后从修改后的URL中创建一个新意图。
答案 1 :(得分:6)
接受的答案很有帮助,但工作代码更好
do {
var resourceValues = URLResourceValues()
resourceValues.isExcludedFromBackup = true
try fileUrl.setResourceValues(resourceValues)
} catch _{
}
正如@Sulthan所提到的,fileURL必须是可变的。