【问题标题】:Check if file is alias Swift检查文件是否为别名 Swift
【发布时间】:2016-01-25 01:53:05
【问题描述】:

如何在 Mac 上检查文件是否为别名?到目前为止,这是我的代码:

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())
    }
}

如何检查文件是否为别名?

【问题讨论】:

  • 你是对的。它正在工作,但我会改变它。问题仍然是别名

标签: macos swift nsfilemanager


【解决方案1】:

有一个简单的解决方案可以完全通过,无需任何指针处理:

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
    }
}

解释:resourceValues(forKeys:) 返回.isAliasFile .isSymbolicLink 用于符号链接,因此您必须确保在检查别名时返回前者而后者不返回。 如果路径不存在,则函数返回 nil。

【讨论】:

    【解决方案2】:

    更新:我最初错误地认为唯一的选择是使用 CoreFoundation (C API) 方法,但事实并非如此 (thanks): Foundation (ObjC API) 类 NSURL 确实提供了一种检测 Finder 别名的方法:

    // OSX 10.9+
    // Indicates if the specified filesystem path is a Finder alias.
    // Returns an optional Boolean: if the lookup failed, such when the path doesn't exist,
    // nil is returned.
    // Example: isFinderAlias("/path/to/an/alias")
    func isFinderAlias(path:String) -> Bool? {
        let aliasUrl = NSURL(fileURLWithPath: path)
        var isAlias:AnyObject? = nil
        do {
            try aliasUrl.getResourceValue(&isAlias, forKey: NSURLIsAliasFileKey)
        } catch _ {}
        return isAlias as! Bool?
    }
    

    [不推荐,除非作为使用UnsafeMutablePointer<Void>的练习]
    以下是使用基于 C 的 CoreFoundation API 的方法:

    • IsAliasFile() 在 OS X 10.4 中已弃用,
    • FSIsAliasFile() 继承,在 10.8 中已弃用。
    • 目前的方法是使用CFURLCopyResourcePropertyForKey(),这在Swift 中处理起来并不有趣,因为必须使用UnsafeMutablePointer<Void> 进行手动内存管理。

    我希望我的内存管理是正确的:

    import Foundation
    
    // Indicates if the specified filesystem path is a Finder alias.
    // Returns an optional Boolean: if the lookup failed, such when the path
    // doesn't exist, nil is returned.
    // Example: isFinderAlias("/path/to/an/alias")
    func isFinderAlias(path:String) -> Bool? {
    
        var isAlias:Bool? = nil // Initialize result var.
    
        // Create a CFURL instance for the given filesystem path.
        // This should never fail, because the existence isn't verified at this point.
        // Note: No need to call CFRelease(fUrl) later, because Swift auto-memory-manages CoreFoundation objects.
        let fUrl = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, false)
    
        // Allocate void pointer - no need for initialization,
        // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
        let ptrPropVal = UnsafeMutablePointer<Void>.alloc(1)
    
        // Call the CoreFoundation function that copies the desired information as
        // a CFBoolean to newly allocated memory that prt will point to on return.
        if CFURLCopyResourcePropertyForKey(fUrl, kCFURLIsAliasFileKey, ptrPropVal, nil) {
    
            // Extract the Bool value from the memory allocated.
            isAlias = UnsafePointer<CFBoolean>(ptrPropVal).memory as Bool
    
            // Since the CF*() call contains the word "Copy", WE are responsible
            // for destroying (freeing) the memory.
            ptrPropVal.destroy()
        }
    
        // Deallocate the pointer
        ptrPropVal.dealloc(1)
    
        return isAlias
    }
    

    【讨论】:

    • 不错的解决方案。在我发布另一个问题之前。如何获取别名指向的文档的文件路径?
    • @Silve2611:这更涉及,所以我建议你问一个新问题;文档说“首先使用 CFURLCreateBookmarkDataFromFile,然后使用 CFURLCreateByResolvingBookmarkData。”如果您仍然需要帮助,请在提出新问题后随时在此处通知我。
    • 好的,我会的。我也做了很大一部分,但我只得到 Fileid 而不是路径。
    • @Silve2611:虽然我的原始答案有效,但我把你引向了错误的道路:is 有一种更方便、基于 Foundation 的方法,使用 @ 987654331@ - 请查看我的更新。
    猜你喜欢
    • 2014-02-07
    • 2018-06-21
    • 2015-09-26
    • 2014-04-27
    • 2016-11-04
    • 2015-09-26
    • 2020-12-27
    • 2013-03-31
    相关资源
    最近更新 更多