ios - 带垂直竖线/竖线的 Objective C URL

标签 ios objective-c nsstring nsstringencoding

我想在 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/

相关文章:

ios - 如何在不更改导航栏色调的情况下更改底部工具栏色调颜色?

ios - (iOS) iPad 应用程序在开始时随机崩溃

ios - C4 创建时间戳

objective-c - 获取日期与 [NSDate date] 相差几个小时

ios - 单击 URL 时 UITextView 崩溃

ios - PHAssetResourceManager writeData 返回错误 1

iphone - 代码花费的时间比预期的要长

ios - 如何从委托(delegate)方法 cellForRowAtIndexPath : 内部调用的方法编辑完成 block 中的 UITableViewCell

ios - 没有得到 String 中 char 的正确索引

objective-c - objective-c : Check if integer/int/number