一、與webView進行交互,調用web頁面中的需要傳參的函數時,參數需要帶單引號,或者雙引號(雙引號需要進行轉義在轉義字符前加\),在傳遞json字符串時不需要加單引號或雙引號。
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
NSString *sendJsStr=[NSString stringWithFormat:@"openFile(\"%@\")",jsDocPathStr];
[webView stringByEvaluatingJavaScriptFromString:sendJsStr];
}
2、在該代理方法中判斷與webView的交互,可通過html裏定義的協議實現
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
3、只有在webView加載完畢之後在能夠調用對應頁面中的js方法。(對應方法如第一條)
4、爲webView添加背景圖片
approvalWebView.backgroundColor=[UIColor clearColor];
approvalWebView.opaque=NO;//這句話很重要,webView是否是不透明的,no爲透明
//在webView下添加個imageView展示圖片就可以了
5、獲取webView頁面內容信息
NSString *docStr=[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.textContent"];//獲取web頁面內容信息,此處獲取的是個json字符串
SBJsonParser *parserJson=[[[SBJsonParser alloc]init]autorelease];
NSDictionary *contentDic=[parserJson objectWithString:docStr];//將json字符串轉化爲字典
6、加載本地文件的方法
第一種方法:
NSString* path = [[NSBundle mainBundle] pathForResource:name ofType:@"html" inDirectory:@"mobile"];//mobile是根目錄,name是文件名稱,html是文件類型
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]]; //加載本地文件
第二種方法:
NSString *resourcePath = [[NSBundle mainBundle] resourcePath];
NSString *filePath = [resourcePath stringByAppendingPathComponent:@"mobile.html"];
NSString *htmlstring=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[uiwebview loadHTMLString:htmlstring baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
7、將文件下載到本地址然後再用webView打開
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];
self.filePath = [resourceDocPath stringByAppendingPathComponent:[NSString stringWithFormat:@"maydoc%@",docType]];
NSData *attachmentData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theUrl]];
[attachmentData writeToFile:filePath atomically:YES];
NSURL *url = [NSURL fileURLWithPath:filePath];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[attachmentWebView loadRequest:requestObj];
//刪除指定目錄下的文件
NSFileManager *magngerDoc=[NSFileManager defaultManager];
[magngerDoc removeItemAtPath:filePath error:nil];
8、處理webView展示txt文檔亂碼問題
if ([theType isEqualToString:@".txt"])
{
//txt分帶編碼和不帶編碼兩種,帶編碼的如UTF-8格式txt,不帶編碼的如ANSI格式txt
//不帶的,可以依次嘗試GBK和GB18030編碼
NSString* aStr = [[NSString alloc] initWithData:attachmentData encoding:NSUTF8StringEncoding];
if (!aStr)
{
//用GBK進行編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000632];
}
if (!aStr)
{
//用GBK編碼不行,再用GB18030編碼
aStr=[[NSString alloc] initWithData:attachmentData encoding:0x80000631];
}
//通過html語言進行排版
NSString* responseStr = [NSString stringWithFormat:
@"<HTML>"
"<head>"
"<title>Text View</title>"
"</head>"
"<BODY>"
"<pre>"
"%@"
"/pre>"
"</BODY>"
"</HTML>",
aStr];
[attachmentWebView loadHTMLString:responseStr baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
return;
}
9 、使用webView加載本地或網絡文件整個流程
1、 Loading a local PDF file into the web view
- (void)viewDidLoad {
[super viewDidLoad];
//從本地加載
NSString *thePath = [[NSBundle mainBundle] pathForResource:@"iPhone_User_Guide" ofType:@"pdf"];
if (thePath) {
NSData *pdfData = [NSData dataWithContentsOfFile:thePath];
[(UIWebView *)self.view loadData:pdfData MIMEType:@"application/pdf"
textEncodingName:@"utf-8" baseURL:nil];
}
//從網絡加載
[self.myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]]];
}
2、The web-view delegate managing network loading
- (void)webViewDidStartLoad:(UIWebView *)webView
{
// starting the load, show the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
// finished loading, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
// load error, hide the activity indicator in the status bar
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
// report the error inside the webview
NSString* errorString = [NSString stringWithFormat:
@"<html><center><font size=+5 color='red'>An error occurred:<br>%@</font></center></html>",
error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];
}
3、Stopping a load request when the web view is to disappear
- (void)viewWillDisappear:(BOOL)animated
{
if ( [self.myWebView loading] ) {
[self.myWebView stopLoading];
}
self.myWebView.delegate = nil; // disconnect the delegate as the webview is hidden
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
/************/
引用自蘋果官方文檔(displaying web content)
10、查找webView中的scrollview
- (void) addScrollViewListener
{
UIScrollView* currentScrollView;
for (UIView* subView in self.webView.subviews) {
if ([subView isKindOfClass:[UIScrollView class]]) {
currentScrollView = (UIScrollView*)subView;
currentScrollView.delegate = self;
}
}
}
11、去掉webView的陰影,做成類似scrollView
- (void)clearBackgroundWithColor:(UIColor*)color
{
// 去掉webview的陰影
self.backgroundColor = color;
for (UIView* subView in [self subviews])
{
if ([subView isKindOfClass:[UIScrollView class]]) {
for (UIView* shadowView in [subView subviews])
{
if ([shadowView isKindOfClass:[UIImageView class]]) {
[shadowView setHidden:YES];
}
}
}
}
}
12、取消長按webView上的鏈接彈出actionSheet的問題
-(void)webViewDidFinishLoad:(UIWebView *)webView
{
[webView stringByEvaluatingJavaScriptFromString:@"document.documentElement.style.webkitTouchCallout = 'none';"];
}
13、取消webView上的超級鏈接加載問題
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
if (navigationType==UIWebViewNavigationTypeLinkClicked) {
return NO;
}
else {
return YES;
}
}
14、一、webView在ios5.1之前的bug:在之前的工程中使用webView加載附件,webView支持doc,excel,ppt,pdf等格式,但這些附件必須先下載到本地然後在加載到webView上纔可以顯示, 當附件下載到本地之後剛剛開始加載到webView上時,此時退出附件頁面會導致程序崩潰。會崩潰是由於webView控件內部沒有把相關代理取消掉,所以導致退出之後程序崩潰。
二、webView在5.1上的bug:之前項目需求要webView可以左右活動,但在往webView上加載頁面時導致頁面加載不全,這個bug是由於webView本身的緩存所致。(還有待研究)
15、在使用webView進行新浪微博分享時,webView會自動保存登陸的cookie導致項目中的分享模塊有些問題,刪除 webView的cookie的方法
-(void)deleteCookieForDominPathStr:(NSString *)thePath
{
//刪除本地cookie,thePath爲cookie路徑通過打印cookie可知道其路徑
for(NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
if([[cookie domain] isEqualToString:thePath]) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] deleteCookie:cookie];
}
}
}
16、在UIWebView中使用flashScrollIndicators
使用UIScrollView時,我們可以使用flashScrollIndicators方法顯示滾動標識然後消失,告知用戶此頁面可以滾動,後面還有更多內容。UIWebView內部依賴於UIScrollView,但是其沒有flashScrollIndicators方法,但可以通過其他途徑使用此方法,如下所示。
for (id subView in [webView subviews])
{ if ([subView respondsToSelector:@selector(flashScrollIndicators)])
{
[subView flashScrollIndicators];
}
}
上述代碼片段可以到webViewDidFinishLoad回調中使用,加載完網頁內容後flash顯示滾動標識。
17、根據內容獲取UIWebView的高度
有時候需要根據不同的內容調整UIWebView的高度,以使UIWebView剛好裝下所有內容,不用拖動,後面也不會留白。有兩種方式可根據加載內容獲取UIWebView的合適高度,但都需要在網頁內容加載完成後纔可以,即需要在webViewDidFinishLoad回調中使用。
①.使用sizeThatFits方法。
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
CGRect frame = webView.frame;
frame.size.height = 1;
webView.frame = frame;
CGSize fittingSize = [webView sizeThatFits:CGSizeZero];
frame.size = fittingSize;
webView.frame = frame;
}
sizeThatFits方法有個問題,如果當前UIView的大小比剛好合適的大小還大,則返回當前的大小,不會返回最合適的大小值,所以使用sizeThatFits前,先將UIWebView的高度設爲最小,即1,然後再使用sizeThatFits就會返回剛好合適的大小。 ②、使用JavaScript
- (void)webViewDidFinishLoad:(UIWebView *)webView
{ CGRect frame = webView.frame;
NSString *fitHeight = [webview stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight;"];
frame.size.height = [fitHeight floatValue];
webView.frame = frame;
}