gpt4 book ai didi

objective-c - addingPercentEncoding 在 Swift 中的工作方式不同

转载 作者:搜寻专家 更新时间:2023-10-30 23:05:09 25 4
gpt4 key购买 nike

我有编码字符串的 obj-C 方法:

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

输入:testswiftapppod://

输出:testswiftapppod%3A%2F%2F

我在 Swift 中编写了相同的方法,但得到了不同的输出:testswiftapppod:%2F%2F

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

由于某种原因冒号没有转换

如何解决这个问题?

我使用 Xcode 8.3

[编辑]

来自文档:

// Returns a new string made from the receiver by replacing all characters not in the allowedCharacters set with percent encoded characters. UTF-8 encoding is used to determine the correct percent encoded characters. Entire URL strings cannot be percent-encoded. This method is intended to percent-encode an URL component or subcomponent string, NOT the entire URL string. Any characters in allowedCharacters outside of the 7-bit ASCII range are ignored. - (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters NS_AVAILABLE(10_9, 7_0);

最佳答案

编辑:

这可能是未记录但有意为之的行为。参见 is `addingPercentEncoding` broken in Xcode 9 beta 2?了解更多详情。


这是一个错误。

我检查了不同的情况,似乎所有 Swift 代码都可以正常工作。请注意,: 允许在 URL 主机中使用,因此不应对其进行编码,并且该错误在 Obj-C 版本中

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

这是一个有趣的错误,因为如果您手动将 ":" 添加到字符集

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

一切开始正常工作。

举报。

请注意,在对 URL 参数进行编码时,不应使用 urlHostAllowed。如果可能,请使用 NSURLQuery 来构建您的 URL。这两个预定义集实际上都不适合 URL 编码。您可以从 urlQueryAllowed 开始,但您仍然需要从中删除一些字符。

参见示例 this answer以获得正确的解决方案或例如 Alamofire library 中的实现.

关于objective-c - addingPercentEncoding 在 Swift 中的工作方式不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43254471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com