2016-04-08 65 views
0

我的應用程序顯示使用專用關鍵字的信息。當用戶觸摸其中一個關鍵字時,該應用將打開一個UIWebView,提供有關該關鍵字的更多信息。下面是創建一個UIWebView代碼:如果URL有片段標識符(#),UIWebview加載請求失敗

NSURLRequest * request = [NSURLRequest requestWithURL: currentURL] ; 
webView = [[UIWebView alloc] initWithFrame: frame]; 
webView.scalesPageToFit=YES; 
[webView setDelegate: self]; 
[webView loadRequest:request]; 

一切工作正常進行簡單的URL「chapter5.html」但如果URL有一個片段標識符「chapter5.html#SECTION3」,頁面根本不打開所有 - 甚至在第五章的開頭都沒有。

我猜測它試圖將整個事情用作文件名並失敗,因爲沒有這樣的文件存在。如果我刪除片段標識符,頁面會顯示,但不在正確的位置。是否有任

  • 獲取到的loadRequest兌現片段標識符,或
  • 做不的loadRequest片段標識符,隨後調整位置,以該片段標識符的方式嗎?

回答

0

您必須拆分片段標識符(hashTag),然後將剩餘的URL提供給UIWebview。你可以這樣說:

NSRange range = [url rangeOfString: @"#"]; 
if (range.location == NSNotFound) { 
    hashTag = nil; 
} 
else { 
    hashTag = [url substringFromIndex: range.location]; 
    url = [url substringToIndex:range.location]; 
} 

然後您設置的viewController作爲UIWebViewDelegate並等待被告知,該頁面已經被加載。一旦加載完成,您可以使用javascript命令轉到由hashTag指定的位置:

- (void) webViewDidFinishLoad: (UIWebView *) localWebView { 

    if (hashTag != nil) { 
     NSString * javaScript = [[NSString alloc] initWithFormat: @"window.location.hash = '%@'", hashTag]; 
     [webView stringByEvaluatingJavaScriptFromString:javaScript]; 
     hashTag = nil; 
    } 

}