Just Lai
Just Lai

Reputation: 325

stringByAddingPercentEscapesUsingEncoding was deprecated in 9.0 .How to do this?

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!

Upvotes: 33

Views: 24360

Answers (5)

Amit Hooda
Amit Hooda

Reputation: 2144

You can use stringByRemovingPercentEncoding instead of stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding

[@"string" stringByRemovingPercentEncoding];

Upvotes: 2

Pankaj Gaikar
Pankaj Gaikar

Reputation: 2483

Here is solution to do in Swift

var encodedString = "Hello, playground".addingPercentEncoding(withAllowedCharacters: .urlFragmentAllowed)

Upvotes: 0

Ishwar Hingu
Ishwar Hingu

Reputation: 558

URL = [[NSString stringWithFormat:@"%@XYZ",API_PATH]stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];

Upvotes: 4

sage444
sage444

Reputation: 5684

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

Upvotes: 84

gnasher729
gnasher729

Reputation: 52602

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.

Upvotes: 3

Related Questions