Getting alias path of file in swift

前端 未结 4 1460
时光说笑
时光说笑 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

    URL variant I need to return nil (not an alias or error) else original - 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
    }
    

提交回复
热议问题