此问题与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
属性,它们都无法帮助我确定NSString路径是本地文件路径还是远程文件URL。
请帮忙!
答案 0 :(得分:1)
尝试各种URL示例后,我认为NSURL类可能不是检查本地文件路径的最终方法。现在我使用以下功能。
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非常有用,打我一些例外。
答案 1 :(得分:0)
为什么不检查文件路径的前缀?
BOOL bIsFileURL = [path hasPrefix: @"/"];
或者,它可能是一条相对路径吗? 在这种情况下,您可以检查远程路径中的http://,https://或ftp://前缀:
NSString *schemeRegex = @"(?i)^(https?|ftp)://.*$";
BOOL bIsRemoteURL;
bIsRemoteURL = [path rangeOfString:schemeRegex
options:NSRegularExpressionSearch].location != NSNotFound;