在Swift 3中设置URL资源值

Gri*_*mxn 3 swift3

我想苹果的转换"ShapeEdit"为例,斯威夫特3,我不能让我的头一轮变化URLsetResourceValue.

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)")
    }
}
Run Code Online (Sandbox Code Playgroud)

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)")
    }      
}
Run Code Online (Sandbox Code Playgroud)

除了Xcode"跳转到定义"之外,我找不到任何文档

设置由给定资源键标识的资源值.

此方法将新资源值写入后备存储.尝试设置只读资源属性或设置资源不支持的资源属性将被忽略,不会被视为错误.此方法目前仅适用于文件系统资源的URL.

URLResourceValues跟踪已设置的属性.这些值是此函数用于确定要写入哪些属性的值.

public mutating func setResourceValues(_ values: URLResourceValues) throws

有没有人对这些变化有任何见解setResourceValue(s)

Sul*_*han 8

目前的宣言NSFileAccessIntent.URL

public var url: URL { get }
Run Code Online (Sandbox Code Playgroud)

这是一个只读属性.

由于Swift 3 URL是a struct,因此您无法对getter返回的不可变值调用mutating方法.要修改URL,首先将其分配给a var.

var url = intent.URL
url.setResourceValues(...)
Run Code Online (Sandbox Code Playgroud)

然后从修改后的URL中创建一个新意图.


Eli*_*rke 7

接受的答案很有帮助,但工作代码更好

do {
    var resourceValues = URLResourceValues()
    resourceValues.isExcludedFromBackup = true
    try fileUrl.setResourceValues(resourceValues)
} catch _{
}
Run Code Online (Sandbox Code Playgroud)

正如@Sulthan所提到的,fileURL必须是可变的.