Getting alias path of file in swift

前端 未结 4 1459
时光说笑
时光说笑 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条回答
  •  一个人的身影
    2020-12-03 20:03

    This is a solution using NSURL.

    It expects an NSURL object as parameter and returns either the original path if the url is an alias or 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
    }
    

    Be aware to provide appropriate entitlements if the function is called in a sandboxed environment.

提交回复
热议问题