Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if NSURL is a directory

Tags:

swift

nsurl

While using Swift I want to check if an NSURL location is a directory. With Objective-C this is not a problem and working find, but when I convert the code to Swift I run into a runtime error.

Maybe someone can point me in the right direction?

import Foundation

let defaultManager = NSFileManager.defaultManager()
let documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as NSURL
let localDocumentURLs = defaultManager.contentsOfDirectoryAtURL(documentsDirectory,
includingPropertiesForKeys: nil, options: .SkipsPackageDescendants, error: nil) as NSURL[]

for url in localDocumentURLs {
    var isError: NSError? = nil
    var isDirectory: AutoreleasingUnsafePointer<AnyObject?> = nil
    var success: Bool = url.getResourceValue(isDirectory, forKey: NSURLIsDirectoryKey, error: &isError)
}
like image 692
alex Avatar asked Jun 13 '14 15:06

alex


3 Answers

In iOS 9.0+ and macOS 10.11+ there is a property in NSURL / URL

Swift:

var hasDirectoryPath: Bool { get }

Objective-C:

@property(readonly) BOOL hasDirectoryPath;

However this is only reliable for URLs created with the FileManager API which ensures that the string path of a dictionary ends with a slash.

For URLs created with custom literal string paths reading the resource value isDirectory is preferable

Swift:

let isDirectory = (try? url.resourceValues(forKeys: [.isDirectoryKey]))?.isDirectory ?? false

Objective-C:

NSNumber *isDirectory = nil;
[url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
NSLog(@"%i", isDirectory.boolValue);
like image 155
vadian Avatar answered Dec 28 '22 08:12

vadian


Swift 3

extension URL {
    var isDirectory: Bool {
        let values = try? resourceValues(forKeys: [.isDirectoryKey])
        return values?.isDirectory ?? false
    }
}
like image 20
Madmoron Avatar answered Dec 28 '22 10:12

Madmoron


that is working quote well on my side:

var error: NSError?
let documentURL : NSURL = NSFileManager.defaultManager().URLForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomain: NSSearchPathDomainMask.UserDomainMask, appropriateForURL: nil, create: true, error: &error)
var isDirectory: ObjCBool = ObjCBool(0)
if NSFileManager.defaultManager().fileExistsAtPath(documentURL.path, isDirectory: &isDirectory) {
    println(isDirectory)
}

NOTE: it checks whether the Documents folder is a folder. you can replace the URL with anything, of course.

like image 34
holex Avatar answered Dec 28 '22 08:12

holex