获取 swift 中文件的别名路径

Getting alias path of file in swift

我无法解析 mac 上的别名 link。我正在检查文件是否是别名,然后我想接收原始路径。相反,我只得到一个文件 ID。 有想法吗?

func isFinderAlias(path:String) -> Bool? {

    var isAlias:Bool? = false // 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.
    print("path before \(path)");
    let fUrl = CFURLCreateWithFileSystemPath(nil, path, CFURLPathStyle.CFURLPOSIXPathStyle, false)
    print("path furl \(fUrl)");
    // 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


        // it will be assigned to by CFURLCopyResourcePropertyForKey() below.
        let ptrDarwin = UnsafeMutablePointer<DarwinBoolean>.alloc(1)

        if ((isAlias) == true){
            if let bookmark = CFURLCreateBookmarkDataFromFile(kCFAllocatorDefault, fUrl, nil){
                let url = CFURLCreateByResolvingBookmarkData(kCFAllocatorDefault, bookmark.takeRetainedValue(), CFURLBookmarkResolutionOptions.CFBookmarkResolutionWithoutMountingMask, nil, nil, ptrDarwin, nil)
                print("getting the path \(url)")
            }
        }

        // Since the CF*() call contains the word "Copy", WE are responsible
        // for destroying (freeing) the memory.
        ptrDarwin.destroy()
        ptrDarwin.dealloc(1)
        ptrPropVal.destroy()
    }

    // Deallocate the pointer
    ptrPropVal.dealloc(1)

    return isAlias
}

编辑: 两个答案都是正确的! 我会选择 mklement0 的答案,因为最初没有说明要求 10.9 上的代码 运行 使它更灵活

这是使用 NSURL 的解决方案。

它需要一个 NSURL 对象作为参数,如果 url 是别名,则 returns 要么是原始路径,要么是 nil.

func resolveFinderAlias(url:NSURL) -> String? {

  var isAlias : AnyObject?
  do {
    try url.getResourceValue(&isAlias, forKey: NSURLIsAliasFileKey)
    if isAlias as! Bool {
      do {
        let original = try NSURL(byResolvingAliasFileAtURL: url, options: NSURLBookmarkResolutionOptions())
        return original.path!
      } catch let error as NSError {
        print(error)
      }
    }
  } catch _ {}

  return nil
}

Swift 3:

func resolveFinderAlias(at url: URL) -> String? {
    do {
        let resourceValues = try url.resourceValues(forKeys: [.isAliasFileKey])
        if resourceValues.isAliasFile! {
            let original = try URL(resolvingAliasFileAt: url)
            return original.path
        }
    } catch  {
        print(error)
    }
    return nil
}

如果在沙盒环境中调用该函数,请注意提供适当的权利。

OS X 10.10+.

上效果很好

这是一个 实现,它也适用于 OS X 10.9:

// OSX 10.9+
// Resolves a Finder alias to its full target path.
// If the given path is not a Finder alias, its *own* full path is returned.
// If the input path doesn't exist or any other error occurs, nil is returned.
func resolveFinderAlias(path: String) -> String? {
  let fUrl = NSURL(fileURLWithPath: path)
  var targetPath:String? = nil
  if (fUrl.fileReferenceURL() != nil) { // item exists
    do {
        // Get information about the file alias.
        // If the file is not an alias files, an exception is thrown
        // and execution continues in the catch clause.
        let data = try NSURL.bookmarkDataWithContentsOfURL(fUrl)
        // NSURLPathKey contains the target path.
        let rv = NSURL.resourceValuesForKeys([ NSURLPathKey ], fromBookmarkData: data) 
        targetPath = rv![NSURLPathKey] as! String?
    } catch {
        // We know that the input path exists, but treating it as an alias 
        // file failed, so we assume it's not an alias file and return its
        // *own* full path.
        targetPath = fUrl.path
    }
  }
  return targetPath
}

注:

  • 与 vadian 的解决方案不同,这将 return 一个值,即使对于 -别名文件,即该文件的 own 完整路径,并采用路径字符串而不是 NSURL 实例作为输入。

  • vadian 的解决方案需要适当的权利才能在沙盒 application/environment 中使用该功能。 似乎这个至少不需要在相同程度上,因为它 运行 在 Xcode Playground 中,与 vadian 的解决方案不同。 如果有人能阐明这一点,请帮忙。

    • 然而,无论哪种解决方案,shell 脚本 运行 与 shebang 行 #!/usr/bin/env swift.
  • 如果您想显式测试给定路径是否是Finder别名,请参阅,它源自vadian,但由于更窄的焦点也 运行s on 10.9.

这是一个 Swift 3 实现,主要基于 vadian 的方法。我的想法是return一个文件URL,所以我有效地将它与fileURLWithPath结合起来。这是一个 NSURL class 扩展,因为我需要能够从现有的 Objective-C 代码调用它:

extension NSURL {
    class func fileURL(path:String, resolveAlias yn:Bool) -> URL {
        let url = URL(fileURLWithPath: path)
        if !yn {
            return url
        }
        do {
            let vals = try url.resourceValues(forKeys: [.isAliasFileKey])
            if let isAlias = vals.isAliasFile {
                if isAlias {
                    let original = try URL(resolvingAliasFileAt: url)
                    return original
                }
            }
        } catch {
            return url // give up
        }
        return url // really give up
    }
}

URL 变体我需要 return nil(不是别名或错误)否则原始 - Swift4

func resolvedFinderAlias() -> URL? {
    if (self.fileReferenceURL() != nil) { // item exists
        do {
            // Get information about the file alias.
            // If the file is not an alias files, an exception is thrown
            // and execution continues in the catch clause.
            let data = try NSURL.bookmarkData(withContentsOf: self as URL)
            // NSURLPathKey contains the target path.
            let rv = NSURL.resourceValues(forKeys: [ URLResourceKey.pathKey ], fromBookmarkData: data)
            var urlString = rv![URLResourceKey.pathKey] as! String
            if !urlString.hasPrefix("file://") {
                urlString = "file://" + urlString
            }
            return URL.init(string: urlString)
        } catch {
            // We know that the input path exists, but treating it as an alias
            // file failed, so we assume it's not an alias file so return nil.
            return nil
        }
    }
    return nil
}