AddPercentEncoding works in Swift

I have an obj-C method that encodes a String:

- (NSString *) encodeValue:(NSString*) unescaped{ return [unescaped stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLHostAllowedCharacterSet]]; } 

input: testswiftapppod://

output: testswiftapppod%3A%2F%2F

I wrote the same method in Swift, but got a different output: testswiftapppod:%2F%2F

 static func encodeValue(unescaped:String!) -> String{ return unescaped.addingPercentEncoding( withAllowedCharacters: CharacterSet.urlHostAllowed)! } 

For some reason, the colon is not converted

How to fix this problem?

I am using Xcode 8.3

[EDIT]

From Documents:

// Returns a new line received from the recipient, replacing all characters not in valid characters specified with percent character encoding. UTF-8 encoding is used to determine the correct percentage of encoded characters. Entire URL strings cannot be percent encoded. This method is for percent coding the URL component or subcomponent of string, and not the entire URL string. Any characters in allowed characters outside the 7-bit ASCII range are ignored. - (nullable NSString *) stringByAddingPercentEncodingWithAllowedCharacters: (NSCharacterSet *) allowedCharacters NS_AVAILABLE (10_9, 7_0);

+5
source share
2 answers

EDIT:

This is probably an undocumented but supposed behavior. See - is this `addPercentEncoding` broken in Xcode 9 beta 2? for more details.


This is mistake.

I went into different cases, it seems that all Swift code is working correctly. Please note that : allowed in the URL, so it should not be encoded and the error is in the Obj-C version .

 NSCharacterSet *set = [NSCharacterSet URLHostAllowedCharacterSet]; NSLog(@"Colon is member: %@", [set characterIsMember:':'] ? @"true" : @"false"); // prints true 

This is an interesting mistake, because if you add ":" to the character set manually

 NSMutableCharacterSet *set = [[NSCharacterSet URLHostAllowedCharacterSet] mutableCopy]; [set addCharactersInString:@":"]; 

Everything starts to work correctly.

Report this.

Please note that when encoding URL parameters you should not use urlHostAllowed . If possible, use NSURLQuery to create the URL . None of the predefined sets are actually suitable for encoding URLs. You can start with urlQueryAllowed , but you still have to remove a few characters from it.

See for example this answer for the correct solution or, for example, for implementation in the Alamofire library .

+5
source

The desired result can be generated:

 func encodeValue(_ string: String) -> String? { guard let unescapedString = string.addingPercentEncoding(withAllowedCharacters: CharacterSet(charactersIn: ":/").inverted) else { return nil } return unescapedString } let encodedString = encodeValue("testswiftapppod://") // testswiftapppod%3A%2F%2F 
0
source

Source: https://habr.com/ru/post/1266409/


All Articles