6

我在解决 mac 上的别名链接时遇到问题。我正在检查文件是否是别名,然后我想接收原始路径。相反,我只得到一个文件 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 上运行的要求,这使得它更加灵活

4

4 回答 4

5

这是一个使用NSURL.

它需要一个NSURL对象作为参数,如果 url 是别名,则返回原始路径或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
}

斯威夫特 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
}

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

于 2015-10-26T15:21:00.930 回答
4

vadian 的答案在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 的解决方案不同,即使对于别名文件,这也将返回一个值,即该文件自己的完整路径,并采用路径字符串而不是NSURL实例作为输入。

  • vadian 的解决方案需要适当的权利才能在沙盒应用程序/环境中使用该功能。与 vadian 的解决方案不同,这似乎至少不需要相同程度的,因为它将Xcode Playground中运行。如果有人可以阐明这一点,请提供帮助。

    • 但是,这两种解决方案可以在带有 shebang line的shell 脚本#!/usr/bin/env swift中运行。
  • 如果您想明确测试给定路径是否为 Finder 别名,请参阅此答案,该答案源自 vadian,但由于其更窄的焦点也适用于 10.9。

于 2015-10-27T06:04:45.563 回答
1

这是一个 Swift 3 实现,主要基于 vadian 的方法。我的想法是返回一个文件 URL,所以我有效地将它与fileURLWithPath. 这是一个 NSURL 类扩展,因为我需要能够从现有的 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
    }
}
于 2017-03-15T16:36:42.400 回答
0

我需要返回 nil(不是别名或错误)的 URL 变体,否则是原始的 - 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
}
于 2017-07-04T14:34:18.277 回答