Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file is alias Swift

How can I check if a file is an Alias on Mac? Here is my code so far:

public func getFiles(){
    let folderPath = "/Users/timeBro/Desktop/testfolder"
    let fileManager = NSFileManager.defaultManager()
    let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(folderPath)!
    
    for url in enumerator.allObjects {
        
        let newurl = NSURL(string: url as! String)
        print("\(url as! String)")
        print(url);
        print(newurl?.isFileReferenceURL())
    }
}

How can I check if the file is an alias?

like image 232
Silve2611 Avatar asked Oct 18 '25 10:10

Silve2611


1 Answers

There is an easy solution which completely gets by without any pointer handling:

extension URL {
    func isAlias() -> Bool? {
        let values = try? url.resourceValues(forKeys: [.isSymbolicLinkKey, .isAliasFileKey])
        let alias = values?.isAliasFile
        let symbolic = values?.isSymbolicLink

        guard alias != nil, symbolic != nil else { return nil }
        if alias! && !symbolic! {
            return true
        }
        return false
    }
}

Explanation: resourceValues(forKeys:) returns .isAliasFile and .isSymbolicLink for symbolic links so you have to make sure the former is returned and the latter isn’t when checking for aliases. If the path doesn’t exist the function returns nil.

like image 53
Tom E Avatar answered Oct 21 '25 12:10

Tom E



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!