我有一个包含“#”的URL字符串。例如,
NSString* urlStr = @"https://developer.apple.com/library/ios/#/legacy/library/documentation/Xcode/Conceptual/ios_development_workflow/10-Configuring_Development_and_Distribution_Assets/identities_and_devices.html#//apple_ref/doc/uid/TP40007959-CH4-SW";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:urlStr];
[[self.webViewSample mainFrame] loadRequest:[NSURLRequest requestWithURL:url]];
使用编码后,“#”将替换为“%23”。如果不使用编码,则NSURL将为零。 我的问题是webview加载了与Browser不同的错误网页。如何处理这个url字符串以便我可以加载正确的网页?
答案 0 :(得分:3)
嗯,是的。这就是你告诉它的事情。NSString* urlStr = @"https://developer.apple.com/library/ios/#/legacy/library/documentation/Xcode/Conceptual/ios_development_workflow/10-Configuring_Development_and_Distribution_Assets/identities_and_devices.html#//apple_ref/doc/uid/TP40007959-CH4-SW"; urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; NSURL* url = [NSURL URLWithString:urlStr];
使用编码后,“#”将替换为“%23”。
如果你不想那样,那就不要那样做了。
如果您不使用编码,则NSURL将为零。
那是因为有两个#,所以你的网址无效。即使NSURL(对狡猾的URL非常宽容)拒绝它也是有道理的。
取出第一个,只有第一个,#:
urlStr = [urlStr stringByReplacingOccurrencesOfString:@"/#"
withString:@""];
(这种方法有点脆弱;您可以通过finding the range of the first match然后only replacing within that range使其更加健壮。)
现在您的网址有效,因此NSURL对此没有任何问题。
答案 1 :(得分:2)
尝试这样,
将#
替换为/#
它的工作
UIWebView *web=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 320, 480)];
NSString* urlStr = @"https://developer.apple.com/library/ios//#/legacy/library/documentation/Xcode/Conceptual/ios_development_workflow/10-Configuring_Development_and_Distribution_Assets/identities_and_devices.html/#//apple_ref/doc/uid/TP40007959-CH4-SW";
urlStr = [urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL* url = [NSURL URLWithString:urlStr];
[web loadRequest:[NSURLRequest requestWithURL:url]];
[self.view addSubview:web];
答案 2 :(得分:2)
所以我想你现在的问题,根本问题是Apple的文档使用了一些相当奇怪的URL。它们包含多个#
字符,这对于URL在技术上无效。第一个是有效的(而且很重要);任何其他人都应该逃脱。
Safari能够处理这个问题,我认为因为它不仅仅是显示/使用原始URL字符串。我迄今发现的最佳解决方案是切换到WebView
的粘贴板处理,如下所示:
- (NSURL *)URLFromString:(NSString *)string;
{
static NSPasteboard *pboard;
if (!pboard) pboard = [[NSPasteboard pasteboardWithUniqueName] retain];
[pboard clearContents];
[pboard writeObjects:@[string]];
NSURL *result = [WebView URLFromPasteboard:pboard];
return result;
}
http://www.mikeabdullah.net/webkit-encode-unescaped-urls.html
的更多详情答案 3 :(得分:1)
问题的根源在于Apple的文档链接不是有效的URL,因此NSURL会做出它应该做的事情而拒绝用它制作URL。
如果用%23替换第二个#,NSURL就像“okaaaaaaaaay”并返回NSURL对象,你的webview将打开正确的页面。