【问题标题】:How can pass multiple parameters in NSURL string in iOS?如何在 iOS 的 NSURL 字符串中传递多个参数?
【发布时间】:2013-02-11 21:31:48
【问题描述】:

我正在该应用程序中开发一个应用程序,我需要在 NSURL 中一次传递多个参数 我的代码是

responseData = [[NSMutableData data] retain];
ArrData = [NSMutableArray array];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@",strfrom,strto,strgo]];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
//NSURLRequest *request1 = [NSURLRequest requestWithURL:
//[NSURL URLWithString:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=1",strfrom,strto]];

上面的代码我需要动态传递多个参数。可能吗 ? 如果是,那怎么办? 谢谢和问候

【问题讨论】:

  • 尝试在添加到 URL 之前创建一个单独的字符串,例如 NSSString *str=[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@",strfrom,strto,strgo],然后将此 str 添加到 URL
  • 首先将所有参数传递给NSString,然后将最终字符串分配给NSURL。
  • 我无法完全理解您的问题。您的问题中仍然传递了多个参数
  • 现在有什么问题?
  • 尝试使用 NSMutableString。

标签: iphone ios objective-c nsurl


【解决方案1】:

在添加到 URL 之前尝试创建一个单独的字符串

 NSSString *strURL=[NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@"‌​,strfrom,strto,strgo];

然后将此 strURL 添加到 URL

NSURL *url = [NSURL URLWithString:strURL];

最后将其添加到请求中,您的代码在向请求中添加 url 的位置错误,URL 不是字符串而是 URL 所以应该是 requestWithURL 而不是 URLWithString,应该是这样的

NSURLRequest *request = [NSURLRequest requestWithURL:url];

【讨论】:

    【解决方案2】:

    这些答案中缺少的一件事是使用[NSString stringByAddingPercentEscapesUsingEncoding:] 来避免在 URL 中使用无效字符:

    NSString *baseURL = [NSString stringWithFormat:@"http://rate-exchange.appspot.com/currency?from=%@&to=%@&q=%@",strfrom,strto,strgo];
    NSURL *url = [NSURL URLWithString:[baseURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    

    【讨论】:

    • 这是一个很好的观点,但请注意 stringByAddingPercentEscapesUsingEncoding 不会对您的字符串进行完整的 URL 编码。它遗漏了诸如 / 和 & 之类的东西。 stackoverflow 有很多关于如何制作自己的示例。
    • 但对我来说,特洛伊木马的答案是作为 URL 的一部分发送 unicode 字的一个组成部分。所以 +1 给他。
    猜你喜欢
    • 2010-10-17
    • 2014-09-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-30
    • 2021-03-05
    • 1970-01-01
    相关资源
    最近更新 更多