[swift-users] getResourceValue
Rod Brown
rodney.brown6 at icloud.com
Fri Jan 6 07:39:31 CST 2017
Hi Jan,
The Swift 3 URL struct has a modernized version of the NSURL API which works far better in Swift. This replaces “getResourceValue(…)” with the API you mentioned: “resourceValues(forKeys:)”.
Previously, in Swift 2, you had to use an separate value, use AutoreleasingUnsafeMutablePointers, conditionally cast and then hope you got the value, and that you used the correct typecast for the key you were asking for:
let url = NSURL(fileURLWithPath: "/Users/me/Desktop/File.png")
var fileType: AnyObject? = nil
do {
try url.getResourceValue(&fileType, forKey: NSURLTypeIdentifierKey)
if let type = fileType as? String {
// Use the file type here
} else {
// Handle error
}
} catch {
// Handle error
}
In Swift 3 with the new Swift URL, the resourceValues(forKeys:) creates a struct with optional type safe properties representing each resource key type, and returns it, allowing you to use if let syntax:
let url = URL(fileURLWithPath: "/Users/me/Desktop/File.png")
if let resourceValues = try? url.resourceValues(forKeys: [.typeIdentifierKey]),
let fileType = resourceValues.typeIdentifier {
// Use the file type here
}
This is a much cleaner, clearer, and type-safe API.
If you want to use the old API, you can simply cast back to NSURL if you require the old behaviour. That said, the new one should serve all your needs and make things so much easier so I recommend you give it a go.
Hope this helps,
Rod
> On 6 Jan 2017, at 6:36 am, J.E. Schotsman via swift-users <swift-users at swift.org> wrote:
>
> Hello,
>
> Is getResourceValue a method or URL or only on NSURL?
> After migrating a project to Swift 3 I have code like
>
> var file:URL
> file.getResourceValue(...) // compiles!
>
> From the documentation and the headers I get the impression that this should not compile!
>
> TIA,
>
> Jan E.
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170107/d35f3c5b/attachment.html>
More information about the swift-users
mailing list