快速获取文件的别名路径 [英] Getting alias path of file in swift

查看:76
本文介绍了快速获取文件的别名路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Mac上无法解析别名链接.我正在检查文件是否为别名,然后要接收原始路径.相反,我只得到一个File-Id. 安莉的想法?

I'm having trouble resolving the alias link on mac. I'm checking if the file is an alias and then I would want to receive the original path. Instead I'm only getting a File-Id. Anly ideas?

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上运行,从而使其更加灵活

Both Answers are correct! I would choose the answer of mklement0 due to the originally not stated requirement that the code run on 10.9 which makes it more flexible

推荐答案

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

  • Unlike vadian's solution, this will return a value even for non-alias files, namely that file's own full path, and takes a path string rather than a NSURL instance as input.

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

vadian's solution requires appropriate entitlements in order to use the function in a sandboxed application/environment. It seems that this one at least doesn't need that to the same extent, as it will run in an Xcode Playground, unlike vadian's solution. If someone can shed light on this, please help.

  • 但是,这两种解决方案都可以在 shell脚本中使用shebang行#!/usr/bin/env swift来运行.
  • Either solution, however, does run in a shell script with shebang line #!/usr/bin/env swift.

如果您要明确测试是否给定路径是Finder别名,请参见此答案,源自vadian的答案,但由于其关注范围较窄,因此也适用于10.9.

If you want to explicitly test whether a given path is a Finder alias, see this answer, which is derived from vadian's, but due to its narrower focus also runs on 10.9.

这篇关于快速获取文件的别名路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆