NSURL: Escape Backslash using NSCharacterSet - objective-c

This may be a duplicate question, but I have checked all over and can't find a working answer for iOS9. -stringByAddingPercentEscapesUsingEncoding has been deprecated. I need to use -stringByAddingPercentEncodingWithAllowedCharacters
Below is the string that needs the backslashes escaped so that the API can authenticate the session and return a response.
NSString *base = #"http://domain.com/interface/?end=imember";
NSCharacterSet *set = [NSCharacterSet URLQueryAllowedCharacterSet];
NSString *key = [#"&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=" stringByAddingPercentEncodingWithAllowedCharacters:set];
The standard URL Character sets don't escape the backslashes, I have tried them all:
URLUserAllowedCharacterSet
URLPasswordAllowedCharacterSet
URLHostAllowedCharacterSet
URLPathAllowedCharacterSet
URLQueryAllowedCharacterSet
URLFragmentAllowedCharacterSet
Please if someone could assist, I am rather new to development. Is it possible to create a custom allowed set which includes the backslash?
EDIT:
This is what the url should look like:
http://domain.com/interface/?end=imember&client_key=KOB3N6KX9JXF2MRPO5U.BRFYM7TYVE\/16KIJVXZA6R7H\/1LD1K\/JYIYG7IZP2HA7NUYOVNT3CJG==&token=SGD7E9B29TQ.8HIITZ37XW3GLK5OGLZNLCDM=

The exact solution for you answer is below.I got it from Zaph's answer.That is the better answer than other answer.
NSString *unescaped = #"http://domain.com/interface/?end=imember"];
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(#"escapedString: %#", escapedString);
URL Encoding Character Sets are
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?#\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?#[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?#[\]^`

Related

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

How to Use An Escape URL String With Formatting in Objective-C

I need to gather data from a website based on the user's input.
searchString is the user inputted value, such as "search this string".
NSString *withoutSpaces = [searchString stringByReplacingOccurrencesOfString:#" " withString:#"%20"];
Here, I need to replace spaces with %20
Next, I need to put the new string without spaces (replaced with %20) into another string.
NSString *unescapedSearchString = [NSString stringWithFormat:
#"website.com/query?=%22%#%22", withoutSpaces];
The site I need is not really "website.com", but that's just an example. I also need the %22 to remain at the beginning and end.
As you can see, I need the %# to format the new withoutSpaces user input into the website URL.
I did a search and found examples but I could not find any with formatting such as in my case using %#.
What's the best way to "escape" the characters and keep my formatted string? Currently, when I try to access data from the website, it comes back as null. However, when I try a string without the %# formatting and an actual value, I successfully retrieve the data from a website.
Any help is greatly appreciated.
You should do things this way:
NSString *searchString = ... // the raw search string with spaces and all
NSString *quoted = [NSString stringWithFormat:#"\"%#\"", searchString];
NSString *escaped = [quoted stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat:#"website.com?query=%#&value=all", escaped];
BTW - the URL seems a little off. There should be a variable name before the = and after the ?.

-[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"]]

stringByReplacingOccurrence does not replace string

I need to parse a FILE URL in my application, and replace the %20 for a SPACE. I am using stringByReplacingOccurance:
NSString *strippedContent = [finalFilePath stringByReplacingOccurrencesOfString:#"%20" withString:#" "];
But when I display strippedContent in an NSLog, all of the %20 strings are still there. Here is an example of the file name I hope to parse:
.../Documents/Inbox/Test%20Doc%20From%20Another%20App.txt
It seems as if NSFileManager cannot find the document when it has the %20 in it.
The file path is being passed from another application through the "Open In..." dialogue. Is there any way to remove the %20 with stringByReplacingOccurrence or when the URL is imported?
NSString provides a method that performs the conversion that you need:
NSString *strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
Yes you should use:
NSString * strippedContent = [finalFilePath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

objective C NSString stringwithformat of a URL

i need my application to send an HTTP request to my server, this is the link, but for some reason, when i create an NSString stringwithformat not all of the string is copied into the string,
this is my URL:
http://192.168.50.204:8080/webapi/originate?sofia/internal/408%25192.168.50.204%20'set:effective_caller_id_number=722772408,bridge:sofia/gateway/012smile/<PHONENUMBER>#212.199.220.21'%20inline%200545890183%200545890183
if i put it in my browser it is working fine.
and this is the code:
self.feedURLString = [NSString stringWithFormat:#"http://192.168.50.204:8080/webapi/originate?sofia/internal/%#%25192.168.50.204%20'set:effective_caller_id_number=722772%#,bridge:sofia/gateway/012smile/%##212.199.220.21'%20inline%20%#%20%#",extention,extention,PhoneNumber,PhoneNumber, PhoneNumber];
keep in mind that there are some %20 and %25 in the URL, maybe it causes the problem...
the string i get in the NSLog is:
feedURLString = http://192.168.50.204:8080/webapi/originate?sofia/internal/408220'set:effective_caller_id_number=722772408,bridge:sofia/gateway/012smile/0545890183#212.199.220.21' 93610576nline2#2#
remove the %20 and %25 from the string
then use the stringByAddingPercentEscapesUsingEncoding command from NSString
string = [sURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
You're right, the %20 are almost certainly causing a problem.
Any places in the string you want an actual % symbol in the result, you should be writing %%.
Another option that some people use is to leave the %s as they are, but use stringByReplacingOccurrencesOfString:withString: to do the substitiation.
eg:
NSString *str = #"http://{HOST}/{USER}/blah";
str = [str stringByReplacingOccurrencesOfString:"{HOST}" withString:hostname];
str = [str stringByReplacingOccurrencesOfString:"{USER}" withString:username];
Try writing the url with the normal characters instead of %20 and %25, then add in your variables, and when you have the complete url string use
[feedURLString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEndocing];
Edit: sorry for double, I guess the anwser was obvious :)