NSURL OData URL - objective-c

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.

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...

Related

Objective-C URL string contains single percent sign

I have a string which ends with percent sign(%),
this string is prepared for an URL request as a parameter:
NSString *parameter = #"/param=%";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL urlWithString:[NSString stringWithFormat:#"http://www.whatev%#",parameter]]];
The request returns nil.
I've tried:
NSString *parameter = #"/param=\uFF05";
//request returns nil
and
NSString *parameter = #"/param=%";
NSString *newParameter = [parameter stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//request returns /param=%25 ...where does 25 come from?!
How could I have only one % converted to a request url?
Any advice would be appreciated.
The percent sign has a special purpose in URL's and is used to encode special characters of all kinds. For example a space ( ) is %20 and the percent sign itself is %25.
http://en.wikipedia.org/wiki/Percent-encoding
The last one should be correct, I assume you have problems using it as a request?
escape sequence for % is %%, so #"/param=%%" should solve the problem

Objective-c URL encode Cloudstack [duplicate]

This question already has answers here:
Objective-C and Swift URL encoding
(13 answers)
Closed 9 years ago.
I am working on an IOS application that needs to communicate with an API (CloudStack). The API requires that each request is signed.
I need to URL encode the parameters and create an HMAC SHA1 hash. Everything works fine until I pass an parameter that contains an plus sign or an colon.
So I guess it is the URL encoding part of my application that isn't working correct. I've searched several sites and tried the provided solutions but without any results.
One of the API specifications is that all the spaces needs to be encoded as "%20" rather than "+".
The API signing guide: http://cloudstack.apache.org/docs/en-US/Apache_CloudStack/4.1.0/html/Developers_Guide/signing-api-requests.html
Currently I am using the following code to URL encode the URL:
-(NSString *)urlenc:(NSString *)val
{
NSString *result = [(NSString *)val stringByReplacingOccurrencesOfString:#"+" withString:#" "];
result = [result stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding];
return result;
}
I call the method like this:
[self urlenc#"2014-01-20T14:02:48+0100"]
In your case the problem probably is both the "+" and ":" character that stringByAddingPercentEscapesUsingEncoding does not encode.
You need to use an encoder that supports more characters, see this SO answer for more complete information.
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding encodes 14 characrters:
`#%^{}[]|\"<> plus the space character as percent escaped.
Here is sample code (iOS7 and above, otherwise see this SO answer):
You may need to change the characters that are encoded.
NSString *testString = #"2014-01-20T14:02:48+0100";
NSString *encodedString1 = [testString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"encodedString1: %#", encodedString1);
NSString *charactersToEscape = #"!*'();:#&=+$,/?%#[]\" ";
NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
NSString *encodedString2 = [testString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];
NSLog(#"encodedString2: %#", encodedString2);
NSLog output:
encodedString1: 2014-01-20T14:02:48+0100
encodedString2: 2014-01-20T14%3A02%3A48%2B0100

Is the | pipe character making URLWithString: fail?

I have this very simple code:
PO(URLString);
url = [NSURL URLWithString:URLString];
PO(url);
NSData * data=[NSData dataWithContentsOfURL:url];
(PO() is my macro to print stuff.)
It works most of the time. Here is the output:
2012-10-08 11:39:28.187 BadgerNew[2475:5007] <0x1f5321f0
BGCRBusinessForDisplay.m:(113)> URLString:
http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:28.193 BadgerNew[2475:5007] <0x1f5321f0
BGCRBusinessForDisplay.m:(115)> url:
http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg
2012-10-08 11:39:30.191 BadgerNew[2475:6b03] <0x1f529f00
BGCRBusinessForDisplay.m:(113)> URLString:
http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true&center=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
2012-10-08 11:39:30.196 BadgerNew[2475:6b03] <0x1f529f00
BGCRBusinessForDisplay.m:(115)> url: (null)
As you see, it works fine for http://id.openrice.com/UserPhoto/photo/0/U/0005Z29E131A230CBA4A42n.jpg and it fails on http://maps.googleapis.com/maps/api/staticmap?&zoom=16&size=160x160&maptype=roadmap&sensor=true&center=-6.187900,106.775429&markers=size:small|color:blue|-6.187900,106.775429
Perhaps the issue is the | in the Google URL. So what should I do with it?
You're right, the | (the "pipe") is the problem.
The Apple docs for URLWithString: say that the relevant external docs are RFCs 2396 and 1738. According to them, | is an "unsafe" character and must always be encoded in a URL. The encoding for it is %7C.
You can correct the pipes in your string manually (if it is a hard-coded string), but the better solution would be to replace them and any other problematic characters using -[NSString stringByAddingPercentEscapesUsingEncoding:].
I found my own solution.
Yap the | is the problem.
So, I do:
URLString = URLString.UTF8Encode;
UTF8Encode is defined in the following:
- (NSString *)UTF8Encode
{
NSString* encodedstring = [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return encodedstring;
}
Yes, it's a category :D

-[NSString stringByAppendingPathComponent:] or just -[NSString stringByAppendingFormat:] for NSStrings for NSURLs?

When calling +[NSURL URLWithString:] I have two options for building my URLs:
[[#"http://example.com" stringByAppendingPathComponent:#"foo"] stringByAppendingPathComponent:#"bar"]
or
[#"http://example.com" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
-[NSString stringByAppendingPathComponent:] seems like the more correct answer, but do I lose anything using -[NSString stringByAppendingFormat:] besides handling double-slashes as in the following case?
// http://example.com/foo/bar
[[#"http://example.com/" stringByAppendingPathComponent:#"/foo"] stringByAppendingPathComponent:#"bar"]
// http://example.com//foo/bar oops!
[#"http://example.com/" stringByAppendingFormat:#"/%#/%#",#"foo",#"bar"];
As you're working with URLS, you should use the NSURL methods:
NSURL * url = [NSURL URLWithString: #"http://example.com"];
url = [[url URLByAppendingPathComponent:#"foo"] URLByAppendingPathComponent:#"bar"]
or in Swift
var url = NSURL.URLWithString("http://example.com")
url = url.URLByAppendingPathComponent("foo").URLByAppendingPathComponent(".bar")
I just ran into a problem with stringByAppendingPathComponent: it removes double slashes everywhere!:
NSString* string1 = [[self baseURL] stringByAppendingString:partial];
NSString* string2 = [[self baseURL] stringByAppendingPathComponent:partial];
NSLog(#"string1 is %s", [string1 UTF8String]);
NSLog(#"string2 is %s", [string2 UTF8String]);
for a baseURl of https://blah.com
and a partial of /moreblah
Produces the two strings:
2012-09-07 14:02:09.724 myapp string1 is https://blah.com/moreblah
2012-09-07 14:02:09.749 myapp string2 is https:/blah.com/moreblah
But for some reason my calls to blah.com to get resource work with the single slash. But it indicates to me that stringByAppendingPathComponent is for paths - NOT urls.
This is on iPhone 4 hardware running iOS 5.1.
I outputted the UTF8 strings as I wanted to make sure that the debugger output I was seeing was believable.
So I guess I am saying - don't use path stuff on URLs, use some home brew or a library.
How about:
[NSString pathWithComponents:#[#"http://example.com", #"foo", #"bar"]]
As pointed out in the comments a / gets stripped from protocol when using the methods from NSPathUtitlites.h, so that is the obvious downfall. The solution I could come up with that is closest to the original one I posted is:
[#[ #"http://example.com", #"foo", #"bar" ] componentsJoinedByString:#"/"]
You will just need to use a literal for the path separator which is what NSString does.
NSString represents paths generically with ‘/’ as the path separator
and ‘.’ as the extension separator.
the point of stringByAppendingPathComponent is to handle double slashes, however, you could do something like:
[[#"http://example.com/" stringByAppendingPathComponent:[NSString stringWithFormat:#"%#/%#", #"foo", #"bar"]]

Extract part of URL

I have an URL and need to extract a part of it.
The url is like this:
http://website.com/get.php?url=http://www.website2.com/index.html?articleID=123456
And I need to extract this part:
http://www.website2.com/index.html?articleID=123456
How would I do this in Objective-C?
First of all, create a NSURL. Then, use the querymethod to get the query string part:
NSURL * url = [ NSURL URLWithString: #"... your url ..." ];
NSString * q = [ url query ];
Then you can use the NSString methods to isolate the needed part.
See the NSString -rangeOfSubstring: and -componentsSeparatedByString: methods.
In this case, you could just split the string at the "=".