ios Objective-C 和 Swift URL 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8086584/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Objective-C and Swift URL encoding
提问by Usi Usi
I have a NSString
like this:
我有一个NSString
这样的:
http://www.
but I want to transform it to:
但我想将其转换为:
http%3A%2F%2Fwww.
How can I do this?
我怎样才能做到这一点?
回答by zaph
To escape the characters you want is a little more work.
转义你想要的字符需要更多的工作。
Example code
示例代码
iOS7 and above:
iOS7及以上:
NSString *unescaped = @"http://www";
NSString *escapedString = [unescaped stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLHostAllowedCharacterSet]];
NSLog(@"escapedString: %@", escapedString);
NSLog output:
NSLog 输出:
escapedString: http%3A%2F%2Fwww
转义字符串:http%3A%2F%2Fwww
The following are useful URL encoding character sets:
以下是有用的 URL 编码字符集:
URLFragmentAllowedCharacterSet "#%<>[\]^`{|}
URLHostAllowedCharacterSet "#%/<>?@\^`{|}
URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|}
URLPathAllowedCharacterSet "#%;<>?[\]^`{|}
URLQueryAllowedCharacterSet "#%<>[\]^`{|}
URLUserAllowedCharacterSet "#%/:<>?@[\]^`
Creating a characterset combining all of the above:
创建一个结合上述所有内容的字符集:
NSCharacterSet *URLCombinedCharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@" \"#%/:<>?@[\]^`{|}"] invertedSet];
Creating a Base64
创建 Base64
In the case of Base64 characterset:
在 Base64 字符集的情况下:
NSCharacterSet *URLBase64CharacterSet = [[NSCharacterSet characterSetWithCharactersInString:@"/+=\n"] invertedSet];
For Swift 3.0:
对于 Swift 3.0:
var escapedString = originalString.addingPercentEncoding(withAllowedCharacters:.urlHostAllowed)
For Swift 2.x:
对于 Swift 2.x:
var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
Note: stringByAddingPercentEncodingWithAllowedCharacters
will also encode UTF-8 characters needing encoding.
注意:stringByAddingPercentEncodingWithAllowedCharacters
也会对需要编码的 UTF-8 字符进行编码。
Pre iOS7 use Core Foundation
Using Core Foundation With ARC:
iOS7 之前使用 Core Foundation
使用 Core Foundation 和 ARC:
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(__bridge CFStringRef) unescaped,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]\" "),
kCFStringEncodingUTF8));
Using Core Foundation Without ARC:
在没有 ARC 的情况下使用 Core Foundation:
NSString *escapedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unescaped,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]\" "),
kCFStringEncodingUTF8);
Note: -stringByAddingPercentEscapesUsingEncoding
will not produce the correct encoding, in this case it will not encode anything returning the same string.
注意:-stringByAddingPercentEscapesUsingEncoding
不会产生正确的编码,在这种情况下它不会编码返回相同字符串的任何内容。
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
encodes 14 characrters:
stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding
编码 14 个字符:
`#%^{}[]|\"<> plus the space character as percent escaped.
`#%^{}[]|\"<> 加上空格字符作为百分比转义。
testString:
测试字符串:
" `~!@#$%^&*()_+-={}[]|\:;\"'<,>.?/AZaz"
encodedString:
编码字符串:
"%20%60~!@%23$%25%5E&*()_+-=%7B%7D%5B%5D%7C%5C:;%22'%3C,%3E.?/AZaz"
Note: consider if this set of characters meet your needs, if not change them as needed.
注意:请考虑这组字符是否满足您的需求,如果没有根据需要更改它们。
RFC 3986 characters requiring encoding (% added since it is the encoding prefix character):
需要编码的 RFC 3986 字符(添加 %,因为它是编码前缀字符):
"!#$&'()*+,/:;=?@[]%"
"!#$&'()*+,/:;=?@[]%"
Some "unreserved characters" are additionally encoded:
一些“非保留字符”被额外编码:
"\n\r \"%-.<>\^_`{|}~"
"\n\r \"%-.<>\^_`{|}~"
回答by larsacus
It's called URL encoding. More here.
-(NSString *)urlEncodeUsingEncoding:(NSStringEncoding)encoding {
return (NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,
(CFStringRef)self,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
CFStringConvertNSStringEncodingToEncoding(encoding));
}
回答by Anonymous White
This is not my solution. Someone else wrote in stackoverflow but I have forgotten how.
这不是我的解决方案。其他人在stackoverflow中写过,但我忘记了怎么写。
Somehow this solution works "well". It handles diacritic, chinese characters, and pretty much anything else.
不知何故,这个解决方案“运行良好”。它可以处理变音符号、中文字符以及其他几乎所有内容。
- (NSString *) URLEncodedString {
NSMutableString * output = [NSMutableString string];
const char * source = [self UTF8String];
int sourceLen = strlen(source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = (const unsigned char)source[i];
if (false && thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
If someone would tell me who wrote this code, I'll really appreciate it. Basically he has some explanation why this encoded string will decode exactly as it wish.
如果有人能告诉我是谁写的这段代码,我会很感激的。基本上他有一些解释为什么这个编码的字符串会完全按照它的意愿解码。
I modified his solution a little. I like space to be represented with %20 rather than +. That's all.
我稍微修改了他的解决方案。我喜欢用 %20 而不是 + 来表示空间。就这样。
回答by Zahi
NSString * encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(NUL,(CFStringRef)@"parameter",NULL,(CFStringRef)@"!*'();@&+$,/?%#[]~=_-.:",kCFStringEncodingUTF8 );
NSURL * url = [[NSURL alloc] initWithString:[@"address here" stringByAppendingFormat:@"?cid=%@",encodedString, nil]];
回答by Neuneed
This can work in Objective C ARC.Use CFBridgingRelease to cast a Core Foundation-style object as an Objective-C object and transfer ownership of the object to ARC .See Function CFBridgingReleasehere.
这可以在 Objective C ARC 中工作。使用 CFBridgingRelease 将 Core Foundation 样式的对象转换为 Objective-C 对象并将对象的所有权转移到 ARC 。请参阅此处的函数 CFBridgingRelease。
+ (NSString *)encodeUrlString:(NSString *)string {
return CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes
(kCFAllocatorDefault,
(__bridge CFStringRef)string,
NULL,
CFSTR("!*'();:@&=+$,/?%#[]"),
kCFStringEncodingUTF8)
);}
回答by Vinod Joshi
Swift iOS:
迅捷iOS:
Just For Information : I have used this:
仅供参考:我用过这个:
extension String {
func urlEncode() -> CFString {
return CFURLCreateStringByAddingPercentEscapes(
nil,
self,
nil,
"!*'();:@&=+$,/?%#[]",
CFStringBuiltInEncodings.UTF8.rawValue
)
}
}// end extension String
回答by Wevah
NSString *str = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)yourString,
NULL,
CFSTR("/:"),
kCFStringEncodingUTF8);
You will need to release or autorelease str
yourself.
您需要自己释放或自动释放str
。
回答by Volomike
Here's what I use. Note you have to use the @autoreleasepool
feature or the program might crash or lockup the IDE. I had to restart my IDE three times until I realized the fix. It appears that this code is ARC compliant.
这是我使用的。请注意,您必须使用该@autoreleasepool
功能,否则程序可能会崩溃或锁定 IDE。我不得不重新启动我的 IDE 三次,直到我意识到修复。看来此代码符合 ARC。
This question has been asked many times, and many answers given, but sadly all of the ones selected (and a few others suggested) are wrong.
这个问题已经被问过很多次,也给出了很多答案,但遗憾的是所有选择的(以及其他一些建议的)都是错误的。
Here's the test string that I used: This is my 123+ test & test2. Got it?!
这是我使用的测试字符串: This is my 123+ test & test2. Got it?!
These are my Objective C++ class methods:
这些是我的 Objective C++ 类方法:
static NSString * urlDecode(NSString *stringToDecode) {
NSString *result = [stringToDecode stringByReplacingOccurrencesOfString:@"+" withString:@" "];
result = [result stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
return result;
}
static NSString * urlEncode(NSString *stringToEncode) {
@autoreleasepool {
NSString *result = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)stringToEncode,
NULL,
(CFStringRef)@"!*'\"();:@&=+$,/?%#[]% ",
kCFStringEncodingUTF8
));
result = [result stringByReplacingOccurrencesOfString:@"%20" withString:@"+"];
return result;
}
}
回答by wrtsprt
Google implements this in their Google Toolbox for Mac. So that's a good place to peak how they're doing it. Another option is to include the Toolbox and use their implementation.
Google 在他们的Google Toolbox for Mac 中实现了这一点。所以这是一个很好的地方来展示他们的工作方式。另一种选择是包含工具箱并使用它们的实现。
Checkout the implementation here. (Which comes down to exactly what people have been posting here).
在此处查看实现。(这归结为人们在这里发布的内容)。
回答by Andy
This is how I am doing this in swift.
这就是我快速执行此操作的方式。
extension String {
func encodeURIComponent() -> String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!
}
func decodeURIComponent() -> String {
return self.componentsSeparatedByString("+").joinWithSeparator(" ").stringByRemovingPercentEncoding!
}
}