IOS之UIWebView的使用(基本知识)

2020-01-14 20:05:32于丽

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:
@""
""
""
""
"%@"
"/pre>"
""
"",
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.easck.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:
@"An error occurred:
%@",
error.localizedDescription];
[self.myWebView loadHTMLString:errorString baseURL:nil];
}