NSURL getResourceValue in swift

前端 未结 5 866
梦如初夏
梦如初夏 2021-02-13 11:54

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

var anyError: NSError? = nil
var rsrc: NSNumber? = nil
var success = url.getResourceValue(&a         


        
5条回答
  •  太阳男子
    2021-02-13 11:59

    Here's a concrete example as an extension of the URL type:

    extension URL {
        var creationDate : Date {
            let url = self as NSURL
            var value : AnyObject?
            try? url.getResourceValue(&value, forKey: .creationDateKey)
            if let date = value as? Date {
                return date
            }
            return .distantPast
        }
    }
    

    For convenience, if the call to getResourceValue() fails, it returns the value .distantPast by default. Using the try? form allows discarding the error which isn't always needed.

提交回复
热议问题