ios 我如何对字符串进行 URL 编码
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8088473/
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
How do I URL encode a string
提问by xonegirlz
I have a URL string (NSString
) with spaces and &
characters. How do I url encode the entire string (including the &
ampersand character and spaces)?
我有一个NSString
带有空格和&
字符的 URL 字符串 ( ) 。如何对整个字符串(包括&
& 字符和空格)进行 url 编码?
回答by chown
Unfortunately, stringByAddingPercentEscapesUsingEncoding
doesn't always work 100%. It encodes non-URL characters but leaves the reserved characters (like slash /
and ampersand &
) alone. Apparently this is a bugthat Apple is aware of, but since they have not fixed it yet, I have been using this category to url-encode a string:
不幸的是,stringByAddingPercentEscapesUsingEncoding
并不总是 100% 有效。它对非 URL 字符进行编码,但单独保留保留字符(如斜杠/
和与号&
)。显然这是Apple 知道的一个错误,但由于他们尚未修复它,我一直在使用此类别对字符串进行 url 编码:
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (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;
}
Used like this:
像这样使用:
NSString *urlEncodedString = [@"SOME_URL_GOES_HERE" urlencode];
// Or, with an already existing string:
NSString *someUrlString = @"someURL";
NSString *encodedUrlStr = [someUrlString urlencode];
This also works:
这也有效:
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(
NULL,
(CFStringRef)unencodedString,
NULL,
(CFStringRef)@"!*'();:@&=+$,/?%#[]",
kCFStringEncodingUTF8 );
Some good reading about the subject:
关于这个主题的一些很好的阅读:
Objective-c iPhone percent encode a string?
Objective-C and Swift URL encoding
Objective-c iPhone百分比编码字符串?
Objective-C 和 Swift URL 编码
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674http://simonwoodside.com/weblog/2009/4/22/how_to_really_url_encode/
http://cybersam.com/programming/proper-url-percent-encoding-in-ios
https://devforums.apple.com/message/15674#15674 http://simonwoodside.com/weblog/2009/4/ 22/how_to_really_url_encode/
回答by Nishant
This might be helpful
这可能会有所帮助
NSString *sampleUrl = @"http://www.google.com/search.jsp?params=Java Developer";
NSString* encodedUrl = [sampleUrl stringByAddingPercentEscapesUsingEncoding:
NSUTF8StringEncoding];
For iOS 7+, the recommended way is:
对于 iOS 7+,推荐的方式是:
NSString* encodedUrl = [sampleUrl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
You can choose the allowed character set as per the requirement of the URL component.
您可以根据 URL 组件的要求选择允许的字符集。
回答by Peter DeWeese
New APIs have been added since the answer was selected; You can now use NSURLUtilities. Since different parts of URLs allow different characters, use the applicable character set. The following example encodes for inclusion in the query string:
自从选择了答案以来,已经添加了新的 API;您现在可以使用 NSURLUtilities。由于 URL 的不同部分允许使用不同的字符,因此请使用适用的字符集。以下示例编码以包含在查询字符串中:
encodedString = [myString stringByAddingPercentEncodingWithAllowedCharacters:NSCharacterSet.URLQueryAllowedCharacterSet];
To specifically convert '&', you'll need to remove it from the url query set or use a different set, as '&' is allowed in a URL query:
要专门转换“&”,您需要将其从 url 查询集中删除或使用不同的集合,因为在 URL 查询中允许使用“&”:
NSMutableCharacterSet *chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
[chars removeCharactersInRange:NSMakeRange('&', 1)]; // %26
encodedString = [myString stringByAddingPercentEncodingWithAllowedCharacters:chars];
回答by Oliver Atkinson
Swift 2.0 Example (iOS 9 Compatiable)
Swift 2.0 示例(iOS 9 兼容)
extension String {
func stringByURLEncoding() -> String? {
let characters = NSCharacterSet.URLQueryAllowedCharacterSet().mutableCopy() as! NSMutableCharacterSet
characters.removeCharactersInString("&")
guard let encodedString = self.stringByAddingPercentEncodingWithAllowedCharacters(characters) else {
return nil
}
return encodedString
}
}
回答by Underdog
ios 7 update
ios 7 更新
NSString *encode = [string stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
NSString *decode = [encode stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
回答by Mike Purcell
I opted to use the CFURLCreateStringByAddingPercentEscapes
call as given by accepted answer, however in newest version of XCode (and IOS), it resulted in an error, so used the following instead:
我选择使用CFURLCreateStringByAddingPercentEscapes
接受的答案给出的调用,但是在最新版本的 XCode(和 IOS)中,它导致错误,因此使用以下代码:
NSString *apiKeyRaw = @"79b|7Qd.jW=])(fv|M&W0O|3CENnrbNh4}2E|-)J*BCjCMrWy%dSfGs#A6N38Fo~";
NSString *apiKey = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (CFStringRef)apiKeyRaw, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8));
回答by Alex
Try to use stringByAddingPercentEncodingWithAllowedCharacters
method with [NSCharacterSet URLUserAllowedCharacterSet]
it will cover all the cases
尝试使用它的stringByAddingPercentEncodingWithAllowedCharacters
方法[NSCharacterSet URLUserAllowedCharacterSet]
将涵盖所有情况
Objective C
目标 C
NSString *value = @"Test / Test";
value = [value stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLUserAllowedCharacterSet]];
swift
迅速
var value = "Test / Test"
value.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLUserAllowedCharacterSet())
Output
输出
Test%20%2F%20Test
Test%20%2F%20Test
回答by gabry
After reading all the answers for this topic and the (wrong) accepted one, I want to add my contribution.
在阅读了该主题的所有答案和(错误的)接受的答案后,我想添加我的贡献。
IFthe target is iOS7+, and in 2017 it should since XCode makes really hard to deliver compatibility under iOS8, the best way, thread safe, fast, amd will full UTF-8 support to do this is:
如果目标是 iOS7+,并且在 2017 年它应该是因为 XCode 确实很难在 iOS8 下提供兼容性,最好的方法是线程安全、快速,amd 将完全支持 UTF-8 来做到这一点:
(Objective C code)
(目标 C 代码)
@implementation NSString (NSString_urlencoding)
- (NSString *)urlencode {
static NSMutableCharacterSet *chars = nil;
static dispatch_once_t pred;
if (chars)
return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
// to be thread safe
dispatch_once(&pred, ^{
chars = NSCharacterSet.URLQueryAllowedCharacterSet.mutableCopy;
[chars removeCharactersInString:@"!*'();:@&=+$,/?%#[]"];
});
return [self stringByAddingPercentEncodingWithAllowedCharacters:chars];
}
@end
This will extend NSString, will exclude RFC forbidden characters, support UTF-8 characters, and let you use things like:
这将扩展 NSString,将排除 RFC 禁止字符,支持 UTF-8 字符,并让您使用以下内容:
NSString *myusername = "I'm[evil]&want(to)break!!!$->àéìòù";
NSLog(@"Source: %@ -> Dest: %@", myusername, [myusername urlencode]);
That will print on your debug console:
这将打印在您的调试控制台上:
Source: I'm[evil]&want(to)break!!!$->àéìòù -> Dest: I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3%A0%C3%A9%C3%AC%C3%B2%C3%B9
来源:Im[evil]&want(to)break!!!$->àéìòù -> Dest:I%27m%5Bevil%5D%26want%28to%29break%21%21%21%24-%3E%C3 %A0%C3%A9%C3%AC%C3%B2%C3%B9
... note also the use of dispatch_once to avoid multiple initializations in multithread environments.
...还要注意使用 dispatch_once 来避免多线程环境中的多次初始化。
回答by Ben Leggiero
Here's a production-ready flexible approach in Swift 5.x:
这是Swift 5.x 中一种可用于生产的灵活方法:
public extension CharacterSet {
static let urlQueryParameterAllowed = CharacterSet.urlQueryAllowed.subtracting(CharacterSet(charactersIn: "&?"))
static let urlQueryDenied = CharacterSet.urlQueryAllowed.inverted()
static let urlQueryKeyValueDenied = CharacterSet.urlQueryParameterAllowed.inverted()
static let urlPathDenied = CharacterSet.urlPathAllowed.inverted()
static let urlFragmentDenied = CharacterSet.urlFragmentAllowed.inverted()
static let urlHostDenied = CharacterSet.urlHostAllowed.inverted()
static let urlDenied = CharacterSet.urlQueryDenied
.union(.urlQueryKeyValueDenied)
.union(.urlPathDenied)
.union(.urlFragmentDenied)
.union(.urlHostDenied)
func inverted() -> CharacterSet {
var copy = self
copy.invert()
return copy
}
}
public extension String {
func urlEncoded(denying deniedCharacters: CharacterSet = .urlDenied) -> String? {
return addingPercentEncoding(withAllowedCharacters: deniedCharacters.inverted())
}
}
Example usage:
用法示例:
print("Hello, World!".urlEncoded()!)
print("You&Me?".urlEncoded()!)
print("#Blessed 100%".urlEncoded()!)
print("Pride and Prejudice".urlEncoded(denying: .uppercaseLetters)!)
Output:
输出:
Hello,%20World!
You%26Me%3F
%23Blessed%20100%25
%50ride and %50rejudice
回答by Rupesh Baldania
This code helped me for encoding special characters
此代码帮助我编码特殊字符
NSString* encPassword = [password stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet alphanumericCharacterSet]];