在使用网络地址时,一般要先将url进行encode成UTF8格式的编码,否则在使用时可能报告网址不存在的错误,这时就需要进行转换。
1.转换函数:
NSString *urlString = [NSString stringWithFormat:@"http://www.baidu.com"];
NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,(CFStringRef)urlString,NULL,NULL,kCFStringEncodingUTF8);
NSURL *url = [NSURL URLWithString:encodedString];
2.通过 C 的字符串来转换
NSString *utf8String = @"http://www.baidu.com";
NSString *unicodeStr = [NSString stringWithCString:[utf8String UTF8String] encoding:NSUnicodeStringEncoding];
3.NSURL 中的转换
有时候获取的url中的中文等字符是乱码,网页内容也是乱码,需要进行一下转码才能正确识别NSString,可以用下面的方法
- (nullable NSString *)stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)enc
- (nullable NSString *)stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)enc
// 1.创建 NSURL 对象
// (1)获取 urlString
NSString *urlString = [NSString stringWithFormat:@"http://www.baidu.com"];
(2)编码转换
// NSString *newStr = [urlString stringByReplacingEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *newStr = [urlString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:newStr];
// 2.创建 NSURLRequest 请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];
4.以上两种方法9.0中已经弃用了,可以使用以下的方法来代替
- (nullable NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet)allowedCharacters
NS_AVAILBLE(10_9,7_0);
@property(nullable,readonly,copy)NSString *stringByRemovingPercentEncoding NS_AVAILABLE(10_9,7_0);
NSString *urlString = [NSString stringWithFormat:@"http://www.baidu.com"];
// 编码转换
NSString *newStr = ursString.stringByRemovingPercentEncoding;
NSURL *url = [NSURL URLWithString:newStr];
// 创建 NSURLRequest 请求对象
NSURLRequest *request = [NSURLRequest requestWithURL:url];