我想使用它,但需要一个解决方案..
NSString *googleAddress = @"http://maps.google.com?q=";
googleAddress = [googleAddress stringByAppendingString:self.address];
googleAddress = [googleAddress stringByAppendingString:@"+"];
googleAddress = [googleAddress stringByAppendingString:self.city];
googleAddress = [googleAddress stringByAppendingString:@",+"];
googleAddress = [googleAddress stringByAppendingString:self.state];
googleAddress = [googleAddress stringByAppendingString:@"&t=h"];
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:googleAddress]];
我需要用加号替换地址,城市和州值中的所有空格,以使谷歌地图能够正常工作。
由于
答案 0 :(得分:4)
googleAddress = [googleAddress stringByReplacingOccurancesOfString:@" " withString:@"+"];
答案 1 :(得分:3)
我会采取不同的方法。我就是这样做的:
NSString * q = [NSString stringWithFormat:@"%@ %@, %@", self.address, self.city, self.state];
NSDictionary * queryDictionary = [NSDictionary dictionaryWithObjectsAndKeys:q, @"q", @"h", @"t", nil];
NSMutableArray * fields = [NSMutableArray array];
for (NSString * key in queryDictionary) {
NSString * value = [queryDictionary objectForKey:key];
NSString * encoded = [NSString stringWithFormat:@"%@=%@", [key URLEncodedString_ch], [value URLEncodedString_ch]];
[fields addObject:encoded];
}
NSString * queryString = [fields componentsJoinedByString:@"&"];
NSString * googleString = [NSString stringWithFormat:@"http://maps.google.com?%@", queryString];
NSURL * googleURL = [NSURL URLWithString:googleString];
[[UIApplication sharedApplication] openURL:googleURL];
可以找到{p> -URLEncodedString_ch
here
为什么这样更好?有几个原因:
&
或=
,该怎么办?地址不寻常,但并非不可能(尤其是街道名称中的&
)。@"UTF-8"
和@"oe"
对象和键添加到字典中以包含在查询字符串中是相当简单的。stringByAddingPercentEscapesUsingEncoding:
答案 2 :(得分:0)
查看NSString的stringByReplacingOccurrencesOfString:withString:
和NSMutableString的replaceOccurrencesOfString:withString:options:range:
。
答案 3 :(得分:0)
这个代码段可能对某些人有用,特别是因为Google对+和%20的处理方式相同。
NSString *escapedUrlString =
[unescapedString stringByAddingPercentEscapesUsingEncoding:
NSASCIIStringEncoding];
来源:http://blog.evandavey.com/2009/01/how-to-url-encode-nsstring-in-objective-c.html