Search code examples
objective-cnsurl

NSURL OData URL


I am passing my OData URL to NSURL like this

NSURL *url = [[NSURL alloc] initWithString:@"https://localhost/odata/Venues?$expand=Fixtures($filter=day(DateTime) eq 9 and month(DateTime) eq 3 and year(DateTime) eq 2020)&$filter=Fixtures/any(f: day(f/DateTime) eq 9 and month(f/DateTime) eq 3 and year(f/DateTime) eq 2020)"];

This URL is not accepted by NSURL, it is becoming NULL

When I give URL like this

NSURL *url = [[NSURL alloc] initWithString:@"https://google.com"];

Then NSURL is accepting the URL... I would like to know how to pass my data URL to NSURL.


Solution

  • That URL contains several characters which need to be escaped. That's absolutely not how URLs work and thus the method initWithString is failing and returning NULL...

    For the majority of the times I've encountered a situation in which I needed to escape a URL the method stringByAddingPercentEscapesUsingEncoding was more than enough since they were relatively short URLs. Nonetheless, yours is a URL with a lot of characters which this method doesn't particularly like. (This includes slash / and ampersand &).

    For this particular scenario probably the following approach would yield best results whilst keeping it simple.

    NSString* unencodedURLString = @"https://localhost/odata/Venues?$expand=Fixtures($filter=day(DateTime) eq 9 and month(DateTime) eq 3 and year(DateTime) eq 2020)&$filter=Fixtures/any(f: day(f/DateTime) eq 9 and month(f/DateTime) eq 3 and year(f/DateTime) eq 2020)";
    
    NSString* urlString = [unencodedURLString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    

    Please let us know if this worked for you...