尝试创建一个URL,在iOS浏览器中打开,如下所示:
NSString *urlStr = [[NSString alloc] initWithFormat:@"http://example.com/#location,data={longitude:%f,latitude:%f}", self.map.userLocation.location.coordinate.longitude, self.map.userLocation.location.coordinate.latitude];
NSURL *url = [[NSURL alloc] initWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
[[UIApplication sharedApplication] openURL:url];
但是,这会将URL打开为http://example.com/%23location,data=%7Blongitude:-1.938274,latitude:52.079151%7D,这会破坏浏览器中的网址加载。我有什么办法可以缓解这种情况吗?即。以不同的方式编码?
答案 0 :(得分:1)
你为什么一开始使用 +stringByAddingPercentEscapesUsingEncoding:
?我不认为该网址中有任何需要转义的内容。只要省略那个电话。
通常,您无法通过百分比转义整个网址字符串。 URL字符串具有结构。不同的角色在不同的组件中是合法的您需要从它组成一个URL,并使用适当的允许和不允许字符集对每个组件进行百分比转义。
如果您可以定位iOS 7及更高版本,我建议您使用NSURLComponents
构建您的网址:
NSURLComponents* components = [[NSURLComponents alloc] init];
components.scheme = @"http";
components.host = @"example.com";
components.path = @"/";
components.fragment = [NSString stringWithFormat:@"location,data={longitude:%f,latitude:%f}", self.map.userLocation.location.coordinate.longitude, self.map.userLocation.location.coordinate.latitude];
NSURL* url = components.URL;
如果你不能只针对iOS7 +,那么在加入片段之前你应该百分之百地转义片段:
NSString* fragment = [[NSString alloc] initWithFormat:@"location,data={longitude:%f,latitude:%f}", self.map.userLocation.location.coordinate.longitude, self.map.userLocation.location.coordinate.latitude];
fragment = [fragment stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString* urlString = [[NSString alloc] initWithFormat:@"http://example.com/#%@", fragment];
NSURL *url = [[NSURL alloc] initWithString:urlStr];
答案 1 :(得分:0)
试试这个。我通常在我的应用程序中的一个单独的类中使用它,它对我有用。
+(NSString *)urlEncodedStringUsingString:(NSString *)string {
NSString *escapedString = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge CFStringRef)string, NULL, CFSTR("!*'();:@&=+$,/?%#[]\" "), kCFStringEncodingUTF8));
return escapedString;
}