Cocoa/Objective-C 从 posix 路径 (path/to/desktop) 获取 HFS 路径 (path:to:desktop) [英] Cocoa/Objective-C get a HFS path (path:to:desktop) from a posix path (path/to/desktop)
问题描述
我使用的是 OSX,Objective-C.
I am on OSX, Objective-C.
我有一个类似
/Users/xxx/Desktop/image2.png
但我将它传递给第三方应用程序,该应用程序需要像
But i pass it to a third party application that excpects finder pathes like
Harddisk:Users:Desktop:image2.png
是否有任何方法(我找不到)来转换这样的路径或将它们从 NSURL 中取出(如果可能,无需修改字符串)?
Is there any method (i can't find) to convert pathes like that or get them out of an NSURL (if possible without string modifying)?
在 AppleScript 中是
In AppleScript it is
return POSIX file "/Users/xxx/Desktop/image2.png" --> Harddisk:Users:xxx:Desktop:image2.png
编辑:这几乎相同:可可路径字符串转换不幸的是,该方法已被弃用...
EDIT: This is pretty much the same: Cocoa path string conversion Unfortunately, the method is deprecated...
推荐答案
目前没有(简单的)替代方案.
There is no (easy) alternative at the moment.
函数 CFURLCopyFileSystemPath
未弃用,仅弃用 enum case kCFURLHFSPathStyle
但原始值 1
仍在工作并避免警告.
The function CFURLCopyFileSystemPath
is not deprecated, only the enum case kCFURLHFSPathStyle
is deprecated but the raw value 1
is still working and avoids the warning.
我正在使用这个类别的NSString
@implementation NSString (POSIX_HFS)
- (NSString *)hfsPathFromPOSIXPath
{
CFStringRef hfsPath = CFURLCopyFileSystemPath((CFURLRef)[NSURL fileURLWithPath:self], 1);
return (NSString *)CFBridgingRelease(hfsPath);
}
@end
该函数也适用于 Swift.Swift 版本更复杂一些,并添加了隐式表示字典的尾随分号,这里作为 URL
的扩展:
The function works also in Swift. The Swift version is a bit more sophisticated and adds the trailing semicolon representing a dictionary implicitly, here as an extension of URL
:
extension URL {
func hfsPath() -> String?
{
if let cfpathHFS = CFURLCopyFileSystemPath(self as CFURL, CFURLPathStyle(rawValue: 1)!) { // CFURLPathStyle.CFURLHFSPathStyle)
let pathHFS = cfpathHFS as String
do {
let info = try self.resourceValues(forKeys: [.isDirectoryKey, .isPackageKey])
let isDirectory = info.isDirectory!
let isPackage = info.isPackage!
if isDirectory && !isPackage {
return pathHFS + ":" // directory, not package
}
} catch _ {}
return pathHFS
}
return nil
}
}
这篇关于Cocoa/Objective-C 从 posix 路径 (path/to/desktop) 获取 HFS 路径 (path:to:desktop)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!