NSURLRequest with url containing special characters

核能气质少年 提交于 2020-01-16 05:35:29

问题


I'm having the same problem as: NSURL with special characters

But tried their solution. Can't get my NSURLRequest to work with åöä characters. If the variable "string" contains åöä the request return null. Also tried with NSISOLatin1StringEncoding.

NSString *encodedString = [string stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *urlString = [NSString stringWithFormat: @"http://suggestqueries.google.com/complete/search?output=firefox&q=%@", encodedString];

NSURL *url = [NSURL URLWithString: urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

This works: http://suggestqueries.google.com/complete/search?output=firefox&q=%C3%A5%C3%B6%C3%A4 (åöä)

Any ideas?

EDIT: Using the debugger the NSURL looks correct:

string  __NSCFString *  @"åäö"  0x0a77cd60
encodedString   __NSCFString *  @"%C3%A5%C3%A4%C3%B6"   0x0a77fc40
url NSURL * @"http://suggestqueries.google.com/complete/search?output=firefox&q=%C3%A5%C3%A4%C3%B6" 0x0a79d1f0

Solved: The problem was not the NSURL it was how the return NSDATA was interpreted.


回答1:


Instead of using

NSURL *url = [NSURL URLWithString: urlString];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

try using

NSString *encoded = [urlString stringByAddingPercentEncodingWithAllowedCharacters: [NSCharacterSet URLQueryAllowedCharacterSet]];
NSURLRequest* request = [NSURLRequest requestWithURL: [NSURL URLWithString: encoded]];


来源:https://stackoverflow.com/questions/24424599/nsurlrequest-with-url-containing-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!