2015-07-22 98 views
0

我想编码特殊字符。它并不适用于所有人。我正在请求包含名称和地址的URL。在请求我对URL进行编码之前,一些特殊字符不是百分比编码的。不编码一些特殊字符iOS

NSString *encodedString = [urlAsString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

url = [[NSURL alloc ] initWithString:encodedString]; 

在此先感谢。

+0

你能否提供一个urlAsString的例子,其中的编码不起作用? – ZeMoon

+1

哪种特殊字符? – Sujay

+0

http:// sample/app/InsertCustomer/name /%2316th%20main && *。地址文本包含#16th main && *。 – VJVJ

回答

0

试试这个。我有类似的问题,它帮助:

- (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; 
} 
0

stringByAddingPercentEscapesUsingEncoding URL编码的问题已经讨论了SO:

https://stackoverflow.com/a/8086845

总之,使用stringByAddingPercentEscapesUsingEncoding是一个坏主意,除非你不想要编码斜杠和其他几个字符(在某些情况下可能是这种情况)。相反,您应该使用Core Foundation的CFURLCreateStringByAddingPercentEscapes函数。查看上面的链接 - 它包含代码示例和更详细的解释。