Search code examples
urlnsurl

cant grab NSURL components when the scheme doesn't have the double slash


I am trying to parse a URL to grab the scheme, path, and parameters using the methods provided in NSURL class reference. I'm noticing however, that if I build the url this way (no double slash after the scheme):    

NSString *urlString = @"customScheme:myPath?parameter=hello&other_parameter=12";
NSURL *url = [NSURL URLWithString:urlString];

I can not grab any of those values from the NSURL. in other words, the methods

path
query

return nil.

If i add the double slashes like this:

NSString *urlString = @"customScheme://myPath?parameter=hello&other_parameter=12";
NSURL *url = [NSURL URLWithString:urlString];

everything works fine. Why is this?

Thanks!


Solution

  • These methods are very clearly documented in Apple's docs:

    path Returns the path of a URL conforming to RFC 1808.

    - (NSString *)path

    The path of the URL, unescaped with the stringByReplacingPercentEscapesUsingEncoding: method. If the receiver does not conform to RFC 1808, returns nil.

    https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSURL_Class/Reference/Reference.html

    And RFC 1808 is very clear about what constitutes a valid relative URL:

    <scheme>://<net_loc>/<path>;<params>?<query>#<fragment>

    http://www.w3.org/Addressing/rfc1808.txt

    If you want to parse mailto: URLs and the like, you'll have to use something other than NSURL to do it.