【问题标题】:Char encoding issue on url, non-english chars -iOSurl 上的字符编码问题,非英文字符 -iOS
【发布时间】:2013-10-29 15:53:35
【问题描述】:

我正在尝试在 youtube 上进行搜索。此代码适用于英文字符。但是当我尝试输入 ö、ü 等非英文字母时,ş 会返回 null。

NSString *kStrJsonURL = [NSString stringWithFormat:@"http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=%@&key=API_KEY&format=5&alt=jsonc&callback=?", self.searchField.text];
    NSURL *url = [NSURL URLWithString:kStrJsonURL];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id getJSON) {
        _JSON = getJSON;
        NSLog(@"%@", _JSON);

    } failure:nil];
    [operation start];

我尝试过像这样对 url 进行编码但不起作用..

[self.searchField.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]

【问题讨论】:

    标签: ios url urlencode url-encoding non-english


    【解决方案1】:

    您是否尝试过 URLEncoding kStrJsonURL?请参阅此帖子的已接受答案。

    How do I URL encode a string

    【讨论】:

      【解决方案2】:

      你的代码应该是这样的:

      //Added this line
      [self.searchField.text stringByReplacingOccurrencesOfString:@" " withString:@"+"];
      //
          NSString *kStrJsonURL = [NSString stringWithFormat:@"http://suggestqueries.google.com/complete/search?hl=en&ds=yt&client=youtube&hjson=t&cp=1&q=%@&key=API_KEY&format=5&alt=jsonc&callback=?", self.searchField.text];
              NSURL *url = [NSURL URLWithString:[kStrJsonURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
              NSURLRequest *request = [NSURLRequest requestWithURL:url];
              AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id getJSON) {
                  _JSON = getJSON;
                  NSLog(@"%@", _JSON);
      
          } failure:nil];
          [operation start];
      

      【讨论】:

      • 我刚试过这个并检查了失败,我收到了这个错误:NSDebugDescription = "Unable to convert data to string around character 1.";
      • 编辑了我的答案。看看有没有帮助。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-03
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多