Getting alias path of file in swift

前端 未结 4 1455
时光说笑
时光说笑 2020-12-03 19:18

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 Fi

4条回答
  •  Happy的楠姐
    2020-12-03 20:03

    vadian's answer works great on OS X 10.10+.

    Here's an implementation that also works on 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
    }
    

    Note:

    • 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'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.

      • Either solution, however, does run in a shell script with shebang line #!/usr/bin/env swift.
    • 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.

提交回复
热议问题