nOOb iOS
nOOb iOS

Reputation: 1394

URL Encoding with NSCharcterSet

I have few video files and image files stored in applications directory.I was using stringByAddingPercentEscapesUsingEncoding: to convert into a legal URL string. Since it is deprecated and we are to use stringByAddingPercentEncodingWithAllowedCharacters: instead, I am not able to get the correct URL for loading the pdf or playing the video. I tried all NSCharacterSet available. It is adding extra %252020 for a space and which is creating a problem.

Using stringByAddingPercentEscapesUsingEncoding

file:///var/mobile/Containers/Data/Application/1392B0FE-F998-45A4-A398-A3ACB47ECE26/Library/Private%20Documents/Sample%20Image%20To%20Be%20Loaded.jpg

Using ** stringByAddingPercentEncodingWithAllowedCharacters**

file:///var/mobile/Containers/Data/Application/1392B0FE-F998-45A4-A398-A3ACB47ECE26/Library/Private%2520Documents/Sample%2520Image%2520To%2520Be%2520Loaded.jpg

And this couldn't find the file and hence couldn't load it. Any help is much appreciated.

Upvotes: 0

Views: 342

Answers (2)

ielyamani
ielyamani

Reputation: 18581

The way you get %2520 is when your url already has a %20 in it, and gets url-encoded again, which transforms the %20 to %2520. %255B is what you get when you encode square bracket twice.

you can try the following code in en empty project:

NSString * str = @"/var/mobile/Containers/Data/Application/1392B0FE-F998-45A4-A398-A3ACB47ECE26/Library/Private Documents/Sample Image To Be Loaded.jpg";
NSString * encodedString = [str stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSLog(@"encodedString = %@", encodedString);
NSString * encodedStringAgain = [encodedString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];
NSLog(@"encodedStringAgain = %@", encodedStringAgain);

It prints:

encodedString = /var/mobile/Containers/Data/Application/1392B0FE-F998-45A4-A398-A3ACB47ECE26/Library/Private%20Documents/Sample%20Image%20To%20Be%20Loaded.jpg

encodedStringAgain = /var/mobile/Containers/Data/Application/1392B0FE-F998-45A4-A398-A3ACB47ECE26/Library/Private%2520Documents/Sample%2520Image%2520To%2520Be%2520Loaded.jpg

All you have to do in your code is :

NSURL *urlToLoad = [NSURL fileURLWithPath: fullPath];

With fullPath being the original string without any encoding.

Upvotes: 1

Karamjeet Singh
Karamjeet Singh

Reputation: 490

You can use

NSString * encodedString = [@"stringURl to encode" stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]];

Upvotes: 0

Related Questions