UIApplication openUrl不使用格式化的NSString

时间:2010-03-28 22:47:54

标签: iphone url iphone-sdk-3.0 uiapplication

我有以下代码来打开谷歌地图:

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlString]];

但它不起作用且没有错误。它只是没有打开。

2 个答案:

答案 0 :(得分:44)

URLWithString需要一个转义百分比的字符串。您的示例网址包含空格,导致创建无NSURL。此外,addressString还可能包含需要转义的字符。首先尝试以百分比形式转义url字符串:

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
NSString *escaped = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:escaped]];  

答案 1 :(得分:5)

需要转义urlString, else [NSURL URLWithString:urlString]将返回nill。

NSString *urlString = [NSString stringWithFormat:@"http://maps.google.com/maps?q=%@, Anchorage, AK",addressString];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding] ]];