检查 NSString 是否为本地文件
Check if NSString is Local File
此问题与 Check if NSURL is Local File 不重复。
我有两种字符串路径指向本地文件路径和远程文件路径,它们可能有一个 HTTP/HTTPS/FTP 方案。
NSString *path = ... ; // like "https://img.server.com/foo.jpeg" or "/Users/myname/Library/Developer/CoreSimulator/Devices/xxxxx/data/Containers/Data/Application/xxxx/Documents/file.txt"
NSURL url1 = [NSURL URLWithString:path];
NSURL url2 = [NSURL fileURLWithPath:path];
我检查了scheme
、fileURL
、isFileReferenceURL
属性,其中none可以帮助我识别NSString路径是本地文件路径还是远程文件URL.
请帮忙!
为什么不只检查文件路径的前缀?
BOOL bIsFileURL = [path hasPrefix: @"/"];
或者,它可以是相对路径吗?
在这种情况下,您可以检查远程路径中的 http://、https:// 或 ftp:// 前缀:
NSString *schemeRegex = @"(?i)^(https?|ftp)://.*$";
BOOL bIsRemoteURL;
bIsRemoteURL = [path rangeOfString:schemeRegex
options:NSRegularExpressionSearch].location != NSNotFound;
在尝试了各种URL示例之后,我认为NSURL class可能不是检查本地文件路径的最终方法。现在我使用以下功能。
BOOL IsLocalFilePath(NSString *path)
{
NSString *fullpath = path.stringByExpandingTildeInPath;
return [fullpath hasPrefix:@"/"] || [fullpath hasPrefix:@"file:/"];
}
它涵盖了/path/to/foo
、file:///path/to/foo
、~/path/to/foo
、../path/to/foo
等本地文件路径。
到目前为止,它对 Unix-like path 非常有用,请告诉我有一些例外。
此问题与 Check if NSURL is Local File 不重复。
我有两种字符串路径指向本地文件路径和远程文件路径,它们可能有一个 HTTP/HTTPS/FTP 方案。
NSString *path = ... ; // like "https://img.server.com/foo.jpeg" or "/Users/myname/Library/Developer/CoreSimulator/Devices/xxxxx/data/Containers/Data/Application/xxxx/Documents/file.txt"
NSURL url1 = [NSURL URLWithString:path];
NSURL url2 = [NSURL fileURLWithPath:path];
我检查了scheme
、fileURL
、isFileReferenceURL
属性,其中none可以帮助我识别NSString路径是本地文件路径还是远程文件URL.
请帮忙!
为什么不只检查文件路径的前缀?
BOOL bIsFileURL = [path hasPrefix: @"/"];
或者,它可以是相对路径吗? 在这种情况下,您可以检查远程路径中的 http://、https:// 或 ftp:// 前缀:
NSString *schemeRegex = @"(?i)^(https?|ftp)://.*$";
BOOL bIsRemoteURL;
bIsRemoteURL = [path rangeOfString:schemeRegex
options:NSRegularExpressionSearch].location != NSNotFound;
在尝试了各种URL示例之后,我认为NSURL class可能不是检查本地文件路径的最终方法。现在我使用以下功能。
BOOL IsLocalFilePath(NSString *path)
{
NSString *fullpath = path.stringByExpandingTildeInPath;
return [fullpath hasPrefix:@"/"] || [fullpath hasPrefix:@"file:/"];
}
它涵盖了/path/to/foo
、file:///path/to/foo
、~/path/to/foo
、../path/to/foo
等本地文件路径。
到目前为止,它对 Unix-like path 非常有用,请告诉我有一些例外。