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)
}
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);
Swift 3
extension URL {
var isDirectory: Bool {
let values = try? resourceValues(forKeys: [.isDirectoryKey])
return values?.isDirectory ?? false
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With