美文网首页
将NSString转换成UTF8编码的NSString

将NSString转换成UTF8编码的NSString

作者: 得_道 | 来源:发表于2020-12-29 15:44 被阅读0次

    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];
    

    相关文章

      网友评论

          本文标题:将NSString转换成UTF8编码的NSString

          本文链接:https://www.haomeiwen.com/subject/rfafoktx.html