检查NSString是否为本地文件

时间:2017-09-20 02:57:34

标签: ios objective-c url filepath

此问题与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];

我检查了schemefileURLisFileReferenceURL属性,它们都无法帮助我确定NSString路径是本地文件路径还是远程文件URL。

请帮忙!

2 个答案:

答案 0 :(得分:1)

尝试各种URL示例后,我认为NSURL类可能不是检查本地文件路径的最终方法。现在我使用以下功能。

BOOL IsLocalFilePath(NSString *path)
{
    NSString *fullpath = path.stringByExpandingTildeInPath;
    return [fullpath hasPrefix:@"/"] || [fullpath hasPrefix:@"file:/"];
}

它涵盖了/path/to/foofile:///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;