我想在 URL 中使用竖线
输入字符串:http://testURL.com/Control?command=dispatch|HOME|ABC:User姓名
-(NSString *)getURLEncodedString:(NSString *)stringvalue{
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[stringvalue UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ':' || thisChar == '/' || thisChar == '?' || thisChar == '=' || thisChar == '|' || 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;
}
调用上述方法后的输出字符串:http://testURL.com/Control?command=dispatch|HOME|ABC:User%20Name
现在,如果我将上面的编码字符串传递给 [[NSURL URLWithString:encodedString];
我收到 Domain=NSURLErrorDomain Code=-1000 "bad URL"UserInfo=0xae9d760 {NSUnderlyingError=0xaec8ed0 "bad URL", NSLocalizedDescription=bad URL}
对这些人有什么意见吗?我希望 URL 看起来像编码字符串。
谢谢!
最佳答案
我真的看不出有什么理由手动编码/转义你的字符串......无论如何,这会工作得很好:
NSString *urlString = @"http://testURL.com/Control?command=dispatch|HOME|ABC:User Name";
NSURL *url = [NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
哪些输出:
http://testURL.com/Control?command=dispatch%7CHOME%7CABC:User%20Name
看来 NSURL
毕竟不喜欢竖线,您没有在您的方法中对其进行编码,因此得到了一个错误的 URL
代码。
关于ios - 带垂直竖线/竖线的 Objective C URL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16963493/