Itachi
Itachi

Reputation: 6070

Check if NSString is Local File

This question is NOT duplicated with Check if NSURL is Local File.

I have two kinds of string path point to local file path and remote file path which may have an HTTP/HTTPS/FTP scheme.

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];

I checked the scheme, fileURL, isFileReferenceURL properties, none of them could help me identify whether the NSString path is a local file path or remote file URL.

Please help!

Upvotes: 1

Views: 969

Answers (2)

Itachi
Itachi

Reputation: 6070

After trying all kinds of URL example, I think the NSURL class may not the final way for this to check the local file path. Now I use the following function.

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

It covers the local file paths like /path/to/foo, file:///path/to/foo, ~/path/to/foo, ../path/to/foo.

It works great for Unix-like path so far, punch me there are some exceptions.

Upvotes: 2

clarus
clarus

Reputation: 2475

Why not just check the prefix of the file path?

BOOL       bIsFileURL = [path hasPrefix: @"/"];

Or, could it be a relative path? In that case, you could check for the http://, https:// or ftp:// prefixes in a remote path:

NSString   *schemeRegex = @"(?i)^(https?|ftp)://.*$";
BOOL       bIsRemoteURL;

bIsRemoteURL = [path rangeOfString:schemeRegex
                           options:NSRegularExpressionSearch].location != NSNotFound;

Upvotes: 0

Related Questions