url上的字符编码问题,非英语字符-iOS

时间:2013-10-29 15:53:36

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

我正在尝试在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]

2 个答案:

答案 0 :(得分:0)

你试过URLEncoding kStrJsonURL吗?请参阅此帖子的已接受答案。

How do I URL encode a string

答案 1 :(得分:0)

您的代码应该是这样的:

//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];