How to convert a classic HFS path into a POSIX path

你离开我真会死。 提交于 2019-11-29 18:06:34

A solution in Obj-C and Swift as category / extension of NSString / String. The unavailable kCFURLHFSPathStyle style is circumvented in the same way as in the linked question.

Objective-C

@implementation NSString (POSIX_HFS)

    - (NSString *)POSIXPathFromHFSPath
    {
        NSString *posixPath = nil;
        CFURLRef fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault, (CFStringRef)self, 1, [self hasSuffix:@":"]); // kCFURLHFSPathStyle
        if (fileURL)    {
            posixPath = [(__bridge NSURL*)fileURL path];
            CFRelease(fileURL);
        }

        return posixPath;
    }

@end

Swift

extension String {

    func posixPathFromHFSPath() -> String?
    {
        guard let fileURL = CFURLCreateWithFileSystemPath(kCFAllocatorDefault,
                                                          self as CFString?,
                                                          CFURLPathStyle(rawValue:1)!,
                                                          self.hasSuffix(":")) else { return nil }
        return (fileURL as URL).path
    }
}

The “reverse” operation of CFURLCopyFileSystemPath() is CFURLCreateWithFileSystemPath(). Similarly as in the referenced Q&A, you have create the path style from the raw enumeration value since CFURLPathStyle.cfurlhfsPathStyle is deprecated and not available. Example:

let hfsPath = "Macintosh HD:Applications:Xcode.app"
if let url = CFURLCreateWithFileSystemPath(nil, hfsPath as CFString,
                                           CFURLPathStyle(rawValue: 1)!, true) as URL? {
    print(url.path) // /Applications/Xcode.app
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!