1

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!

Itachi
  • 5,777
  • 2
  • 37
  • 69
  • Is your question asking how to determine whether you should create an `NSURL` from an `NSString` using either `URLWithString:` or `fileURLWithPath:` depending on the value of the string? – rmaddy Sep 20 '17 at 03:01
  • Yes, `URLWithString:` is used for general remote file url, `fileURLWithPath:` is used for the local file path, I think. I need to know whether the source path is a local file path or not. – Itachi Sep 20 '17 at 03:09

2 Answers2

2

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.

Itachi
  • 5,777
  • 2
  • 37
  • 69
0

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;
clarus
  • 2,455
  • 18
  • 19
  • Yes, I want a more general string path function to validate the local file path. The regular expression doesn't help here as the url scheme could be [any types](https://en.wikipedia.org/wiki/URL). – Itachi Sep 20 '17 at 07:22
  • Then use this. You can't have a : in a file path, but any url scheme will have one. bIsRemoteURL = [path rangeOfString:@":" options:NSLiteralSearch].location != NSNotFound; On the other hand, if the remote URL won't have a scheme, then you can't distinguish between a file or remote URL. You could check to see if a local file with the name exists, but that's problematic because, without the scheme, a file could also exist with the remote url path. – clarus Sep 20 '17 at 07:37