Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSURL getResourceValue in swift

Tags:

url

swift

Having trouble figuring out how to make the following call in swift:

var anyError: NSError? = nil
var rsrc: NSNumber? = nil
var success = url.getResourceValue(&rsrc, forKey:NSURLIsUbiquitousItemKey, error:&anyError)

The above does not compile:

Cannot convert the expression's type 'Bool' to type 'inout Bool'

So I tried this:

var anyError: NSError? = nil
var rsrc: AutoreleasingUnsafePointer<AnyObject?> = nil
var success = url.getResourceValue(rsrc, forKey:NSURLIsUbiquitousItemKey, error:&anyError)

but this generates EXC_BAD_ACCESS runtime error.

How do I pass in the expected first arg as AutoreleasingUnsafePointer<AnyObject?> (which should point to a boolean NSNumber according to doc), and then be able to check its expected Bool value ?

like image 895
CMont Avatar asked Jun 25 '14 04:06

CMont


2 Answers

You need to make rsrc an optional AnyObject and pass it by reference like so:

var anyError: NSError?
var rsrc: AnyObject?
var success = url.getResourceValue(&rsrc, forKey:NSURLIsUbiquitousItemKey, error:&anyError)

Note: You do not need to initialize Optionals to nil, they are set to nil by default.

If you then want to check if the value is an NSNumber you can then do a conversion:

if let number = rsrc as? NSNumber {
    // use number
}
like image 118
drewag Avatar answered Nov 09 '22 23:11

drewag


Here is drewag's code updated for Swift 2.0

    do {
        var rsrc: AnyObject?
        try element.getResourceValue(&rsrc, forKey: NSURLIsDirectoryKey)
        if let number = rsrc as? NSNumber {
            if number == true {
                // do something
            }
        }
    } catch {
    }
like image 7
Eli Burke Avatar answered Nov 10 '22 00:11

Eli Burke