31

I'm a junior developer, and I got a code for this:

(NSString *)encodedStringFromObject:(id)object {
    return [[object description] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];    
}

But in 9.0 have to use stringByAddingPercentEncodingWithAllowedCharacters.

How Could I transfer this code ? I need help, Thanks!

Finrod
  • 2,425
  • 4
  • 28
  • 38
Just Lai
  • 305
  • 1
  • 3
  • 9
  • in iOS9 stringByAddingPercentEscapesUsingEncoding has been replaced with stringByAddingPercentEncodingWithAllowedCharacters: – Jiri Zachar Dec 01 '15 at 08:26

5 Answers5

84

If you want just fast example look at this code:

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

Also check List of predefined characters sets

If you want explanation read the documents or at least this topic: How to encode a URL in Swift

Community
  • 1
  • 1
sage444
  • 5,661
  • 4
  • 33
  • 60
  • yes , i use your sample transfer my code to . return [[object description] stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLFragmentAllowedCharacterSet]]; than it's working , thank you very much! – Just Lai Dec 01 '15 at 09:56
  • un...how to mark it.. this is my first time to use stack overflow , click the accept button? – Just Lai Dec 01 '15 at 10:05
  • 1
    @JustLai thank you, I see you found way, I also recommend you spend a moment and take a tour. (top right near search help->tour). And good stackoverflowing:) – sage444 Dec 01 '15 at 10:08
  • Thanks for your suggest , it's useful for me! – Just Lai Dec 01 '15 at 10:11
4
URL = [[NSString stringWithFormat:@"%@XYZ",API_PATH]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Ishwar Hingu
  • 562
  • 7
  • 14
3

You'd read the spec for both functions. Then you would find out for what purpose characters are replaced with escape sequences. From there you would find out the set of allowed characters, which must be documented somewhere.

That's an essential part of changing from junior to normal to senior developer: Find out exactly what your code is supposed to do, which should be defined somewhere, and then make it do what it should do.

stringByAddingPercentEscapesUsingEncoding is probably deprecated because it doesn't know which characters are allowed and sometimes gives the wrong results.

gnasher729
  • 51,477
  • 5
  • 75
  • 98
2

You can use stringByRemovingPercentEncoding instead of stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding

[@"string" stringByRemovingPercentEncoding];

Amit Hooda
  • 2,133
  • 3
  • 23
  • 37
0

Here is solution to do in Swift

var encodedString = "Hello, playground".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)
Pankaj Gaikar
  • 2,357
  • 1
  • 23
  • 29