我有一个包含大约10个链接(项目)的静态网页。我的需求很简单:当用户点击链接时,在新的webview中打开。当用户返回菜单时,再次单击此链接,之前加载打开的webview(无需添加具有相同URL的新webview)。这是我的解决方案:保存已加载的网址,并在预加载新点击时进行检查。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
if(![self checkIsAlreadyLoaded:request]) {
// load new webview
[self addWebView:request];
return NO;
}
}
return YES;
}
- (BOOL)checkIsAlreadyLoaded:(NSURLRequest *)request {
NSString *urlToCheck = request.URL.absoluteString;
NSLog(@"URL to check: %@", urlToCheck);
for (int i = 0; i < self.visitedURLsArray.count; i++) {
if([[self.visitedURLsArray objectAtIndex:i] isEqualToString:request.URL.absoluteString]) {
NSLog(@"URL Found!");
return YES;
}
}
NSLog(@"*** NOT MATCHING ***");
return NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if(![self.visitedURLsArray containsObject:webView.request.URL.absoluteString]) {
NSLog(@"saved url: %@", webView.request.URL.absoluteString);
[self.visitedURLsArray addObject:webView.request.URL.absoluteString];
}
}
我的一些链接是Google链接,我对这些链接有疑问。例如:Google+网址:
由于保存的网址始终与起始网址不同,我无法打开保存的网址,我该如何处理?
答案 0 :(得分:0)
在重定向之前保存网址//在@interface
中保存@property NSURL *urlBeingLoaded;
....
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if(navigationType == UIWebViewNavigationTypeLinkClicked) {
if(![self checkIsAlreadyLoaded:request]) {
// load new webview
self.urlBeingLoaded = request.URL;
[self addWebView:request];
return NO;
}
}
return YES;
}
- (BOOL)checkIsAlreadyLoaded:(NSURLRequest *)request {
NSString *urlToCheck = request.URL.absoluteString;
NSLog(@"URL to check: %@", urlToCheck);
for (int i = 0; i < self.visitedURLsArray.count; i++) {
if([[self.visitedURLsArray objectAtIndex:i] isEqualToString:request.URL.absoluteString]) {
NSLog(@"URL Found!");
return YES;
}
}
NSLog(@"*** NOT MATCHING ***");
return NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
if(![self.visitedURLsArray containsObject:_urlBeingLoaded]) {
NSLog(@"saved url: %@", _urlBeingLoaded);
[self.visitedURLsArray addObject:self.urlBeingLoaded];
}
}