您当前的位置:首页 > 建站知识 > 编程知识

NSURL的中文问题

发布时间: 2020-06-21 │ 浏览:2883 

当NSURL中含有中文时OC是不能识别的,会得到一个nil值。

网上有很多解决方法都是老版本,现在已被iOS作废了,所以有必要更新一下代码:

    NSString *urlString = [NSString stringWithFormat:@"https://www.workneed.com/post.html?login_id=%",self.login_id];
    NSString *charactersToEscape = @"!@#$^%*+,;'\"`<>()[]{}";//这是要转码的字符集,象/?&这三个字符是url中特有的,不用转码
    NSCharacterSet *allowedCharacters = [[NSCharacterSet characterSetWithCharactersInString:charactersToEscape] invertedSet];
    NSString *encodeString = [urlString stringByAddingPercentEncodingWithAllowedCharacters:allowedCharacters];//相当于其它语言的urlEncode,但用OC来表达,代码太长了,长到都不想记,直接复制了
    NSURL *url = [NSURL URLWithString:encodeString];