gpt4 book ai didi

ios - initWithString 和 stringByAddingPercentEscapesUsingEncoding 中断 URL iOS

转载 作者:行者123 更新时间:2023-11-29 02:43:14 24 4
gpt4 key购买 nike

尝试创建一个 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 ,这会中断浏览器中的 URL 加载。我能做些什么来缓解这种情况吗? IE。以不同的方式编码?

最佳答案

为什么首先要使用 +stringByAddingPercentEscapesUsingEncoding:?我认为该 URL 中没有任何内容需要转义。只需忽略该调用即可。

一般来说,您不能对整个 URL 字符串进行百分号转义。 URL 字符串具有结构。不同的字符在不同的组件中是合法的。您需要从它的组件组成一个 URL,并使用适当的一组允许和不允许的字符对每个组件进行百分号转义。

如果您可以针对 iOS 7 及更高版本,我建议您使用 NSURLComponents 来构建您的 URL:

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+,你应该在将片段与 URL 的结果结合之前对片段进行百分比转义:

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];

关于ios - initWithString 和 stringByAddingPercentEscapesUsingEncoding 中断 URL iOS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25476512/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com