6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

2バイト文字列のURL変換

Last updated at Posted at 2014-03-17

例えば「あいうえお」で検索した結果をwebViewで表示しようと以下を実行してみるとurl = nil; になってしまう件。

sample_old.m
NSString *baseString = @"あいうえお";
NSString *urlString = [NSString 
	stringWithFormat:@"https://www.google.co.jp/#q=%@", 
	baseString];
NSURL   *url = [NSURL URLWithString: urlString];
NSURLRequest    *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];

本家のクラスリファレンスを見るに、NSURLはRFC 1738 と 1808に準拠してないといけないらしく、平たく言うとURLencodeされている必要がありますよ、と。 そんな訳で、修正してうまくいったコードがこちら。

sample_new.m
NSString *baseString = @"あいうえお";
NSString *escapedString = 
(NSString *)CFBridgingRelease(
	CFURLCreateStringByAddingPercentEscapes(
		kCFAllocatorDefault,
		(CFStringRef) baseString,
		NULL,
		(CFStringRef)@"!*'();:@&=+$,/?%#[]",
		kCFStringEncodingUTF8));
NSString *url = [NSString 
	stringWithFormat:@"https://www.google.co.jp/#q=%@", 
	escapedString];
NSURLRequest    *urlRequest = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:urlRequest];
6
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?