• UIWebView 网页视图


     今天做项目遇到了浏览网页这个功能,也就用到了 UIWebView 这个类
    那么我们就来看看这个类都有什么东西
    其实这个类还是比较简单的
    UIWebView 继承于UIView
    利用这个类可以简单的实现网页浏览
    下面先看一下属性
     

    @property(nonatomic, assign) id<UIWebViewDelegate> delegate             //类的代理
    @property(nonatomic, readonly, retain) NSURLRequest * request           //当前显示页面的URL请求
      
    @property(nonatomic, readonly, getter=isLoading) BOOL loading           //当前网页是否是正在加载状态
    @property(nonatomic, readonly, getter=canGoBack) BOOL canGoBack         //从当前网页是否能返回上一网页
    @property(nonatomic, readonly, getter=canGoForward) BOOL canGoForward   //从当前网页能否前进
    @property(nonatomic) BOOL scalesPageToFit                               //网页内容是否自适应大小
    @property(nonatomic, readonly, retain) UIScrollView * scrollView        //与当前web视图 相关联的滚动视图
    @property(nonatomic) BOOL suppressesIncrementalRendering                //是否网页内容下载完毕才开始渲染web视图,默认为NO
    @property (nonatomic) BOOL keyboardDisplayRequiresUserAction            //是否在web页面响应用户输入弹出键盘,默认为YES
    @property(nonatomic) UIDataDetectorTypes dataDetectorTypes              //把网页上的内容转换为可点击的链接
    enum {
       UIDataDetectorTypePhoneNumber   = 1 << 0,
       UIDataDetectorTypeLink          = 1 << 1,
       UIDataDetectorTypeAddress       = 1 << 2,
       UIDataDetectorTypeCalendarEvent = 1 << 3,
       UIDataDetectorTypeNone          = 0,
       UIDataDetectorTypeAll           = NSUIntegerMax
    };
    @property(nonatomic) BOOL allowsInlineMediaPlayback                   //这个值决定了用内嵌HTML5播放视频还是用本地的全屏控制。

    //为了内嵌视频播放,不仅仅需要在这个页面上设置这个属性, //还必须的是在HTML中的video元素必须包含webkit-playsinline属性。默认使NO。 @property(nonatomic) BOOL mediaPlaybackRequiresUserAction //在iPhone和iPad上默认使YES。这个值决定了HTML5视频可以自动播放还是需要用户去启动播放 @property(nonatomic) BOOL mediaPlaybackAllowsAirPlay //这个值决定了从这个页面是否可以Air Play。 在iPhone和iPad上默认使YES。


     
     下面来看一下方法
     

     加载数据
     - (void)loadRequest:(NSURLRequest *)request                                 //加载URL数据请求
    - (void)loadHTMLString:(NSString *)string baseURL:(NSURL *)baseURL           //设置主页,主页内容为baseURL链接内容
    - (void)loadData:(NSData *)data MIMEType:(NSString *)MIMEType textEncodingName:(NSString *)encodingName baseURL:(NSURL *)baseURL
    //设置主页内容,MIME类型,编码的内容和基本的URL。
    //data数据为主页内容 
    
    - (void)stopLoading                                                          //停止加载数据
    - (void)reload                                                               //加载当前页数据
    

    网页切换 - (void)goBack //后退一页 - (void)goForward //前进一页
    运行Java脚本
    - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script //返回运行脚本语言的结果。

      JavaScript的执行时间被限定在10秒钟,如果执行时间超过10秒,那么页面就停止执行这个脚本。
      JavaScript的执行或许能够阻塞主线程,所以当脚本执行的时候不允许用户影响页面的加载。
      JavaScript的内存分配被限制在10M,如果超出这个限制那么页面会发生异常。

    ===============================================================

    UIWebView加载本地HTML文件

    一.准备HTML文件及其资源文件

    使用UIWebView加载本地的HTML文件 index.html,在index.html中引用了本地的图片、CSS文件、JS文件以及外部的图片。
    index.html内容如下

    <html> 

      <head>
      
        <link href="index.css" rel="stylesheet" type="text/css">
        <script type="text/javascript"language="javascript"src="index.js">
      </head>

      <body>
        <p>This is local Image<
    /p>

        <img src="Smiley.png" width="50" height="50" /> <hr/> <p>this is local image from CSS.</p> <div id="myimage"> </div>

        <hr/> <p>this is external image.</p>
      
        <img src="http://imglf9.ph.126.net/F37NyhuzmvHJChMARbFmHA==/1010495166409149719.jpg" width="300" height="200" />
      <
    /body>

    </html>
     

    HTML中会显示3张图片,第一张是html从本地读取的图片,第二张是通过CSS从本地读取的图片,第三张是通过绝对地址从外部读取的图片。
    index.css文件内容如下:

    body { padding: 0px; margin: 0px; }
    p { font-size: 15px; color: #808080; font-family: Arial, Helvetica, sans-serif; } 
    #myimage
    { background-image: url(SmallSmiley.png); background-repeat: repeat-x; }

    index.js文件内容为:

    function rewrite() { document.write("This text was written by an external script!") }

    index.js

    二.加载本地HTML文件

    将html文件及相关资源添加到项目中

    需要注意的是,把js文件加入到项目时会默认将其当做需要编译的代码,需要在TARGETS->Build Phases中的”Compile Sources”中找到该js文件,并将其移到上面的Copy Bundle Resources中。

    然后在代码中可以用两种方法加载。
    1.第一种方式,使用loadRequest:方法加载本地文件NSURLRequest

    NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]; 
    NSURL* url = [NSURL fileURLWithPath:path]; 
    NSURLRequest* request = [NSURLRequest requestWithURL:url] ; 
    [webView loadRequest:request];
     

    2.第二种方式,使用loadHTMLString:baseURL:加载HTML字符串

    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]; 
    NSString *path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString *html = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; 
    [webView loadHTMLString:html baseURL:baseURL];
     

    加载后的显示效果如下,本地图片,CSS加载的本地图片,以及外部图片都可以正常显示。

    在HTML页面加载完毕后,我们可以使用UIWebView的stringByEvaluatingJavaScriptFromString:方法执行javascript语句。如下:

    - (void)webViewDidFinishLoad:(UIWebView *)webView{ [webView stringByEvaluatingJavaScriptFromString:@"rewrite();"]; }

    三.关于baseURL

    loadHTMLString:baseURL:方法的第二个参数是baseURL,baseURL即HTML字符串中引用到资源的查找路径,没有引用外部资源时,可以直接传nil;若引用了外部资源,一般情况下使用mainBundle的路径即可,即

    NSURL *baseURL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]];

    这是因为,Xcode项目中的文件路径都是虚拟的,在APP中实际不存在,即在APP中,几乎所有的文件都可以从mainBundle根目录下直接访问,当然,例外总是存在的。

    在将文件/文件夹加入到项目时,有这样两个选项“Create Folder References for any added folders”和“Recursively create groups for any added folders”。

    默认情况下为第一种,即所有加入到项目的文件都会在mainBundle根路径下,即不管加入项目的文件的目录结构如何,在APP中都可以通过 mainBundlePath/filename来访问到;如果采用第二种方式,则就会保留相对路径,需要通过mainBundlePath/path /filename来访问。通过这两种方式到项目的文件夹显示具有不同的颜色,如下

    images1目录是使用“Create Folder References for any added folders”增加的目录,images2目录是使用“Recursively create groups for any added folders”增加的目录。

    获取images1目录下文件的代码如下:

    NSString* image1Path = [[NSBundle mainBundle] pathForResource:@"image1"ofType:@"jpg"]; 
    NSString* image11Path = [[NSBundle mainBundle] pathForResource:@"image11"ofType:@"jpg"];
     

    images1和images11目录实际是不存在的,下面代码返回的路径都是nil

    NSString* images1Dir = [[NSBundle mainBundle] pathForResource:@"images1"ofType:nil]; 
    NSString* images11Dir = [[NSBundle mainBundle] pathForResource:@"images11"ofType:nil];
     

    对于images2目录以及目录下的文件路径,其在APP中仍然保持了目录关系,就不能用上述方法获取,而且目录路径是真实存在的,应该使用的代码如下:

    NSString* images2Path = [[NSBundle mainBundle] pathForResource:@"image2"ofType:@"jpg"inDirectory:@"images2"]; 
    NSString* image22Path = [[NSBundle mainBundle] pathForResource:@"image22"ofType:@"jpg"inDirectory:@"images2/images22"];
    NSString* images2Dir = [[NSBundlemainBundle] pathForResource:@"images2"ofType:nil];
    NSString* images2Dir = [[NSBundle mainBundle] pathForResource:@"images22"ofType:nilinDirectory:@"images2"];
     

    还有一种比较特殊的目录是以.bundle为后缀的目录,将其加入到项目是不管选择的是哪个选项,其都会保持其目录结构。

    对子bundle的访问,可以通过同images2目录相同的方法访问,但一般情况下是先获取到子Bundle,再通过子Bundle获取到其里面的资源。

    NSBundle *bundle = [NSBundle bundleWithPath:[[NSBundle mainBundle] pathForResource:@"images" ofType:@"bundle"]];
    NSString* imagebPath = [bundle pathForResource:@"imageb"ofType:@"jpg"]; 
    NSString* imagebbPath = [bundle pathForResource:@"imagebb"ofType:@"jpg" inDirectory:@"imagesb"];
     

    参考:
    How to load local HTML resouces in UIWebView
    UIWebView and JavaScript
    UIWebView如何加载CSS?
    UIWebView – Loading External Images and CSS
    Using iPhone UIWebView Class with local CSS & JavaScript resources
    UIWebView – The Most Versatile Class in UIKit

    http://www.winddisk.com/2012/09/24/uiwebview_load_local_html_file/

    ================================================

    @interface PTAUserProtocalVC ()
    {
        UIWebView *_webView;                //显示协议内容的 WebView
        
    }
    
    @end
    
    @implementation PTAUserProtocalVC
    
    - (void)viewDidLoad {
        [super viewDidLoad];
        [self.navTitle setText:@"用户服务协议"];
        
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, KTopViewHeigh, Main_Screen_Width, Main_Screen_Height-KTopViewHeigh)];
        [self.view addSubview:_webView];
        
        
        NSString* path = [[NSBundle mainBundle] pathForResource:@"protocal" ofType:@"html"];
        NSURL* url = [NSURL fileURLWithPath:path];
        NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
        [_webView loadRequest:request];
    }
    
    
    @end
  • 相关阅读:
    python第十一天
    python第七天(字符编码,字符与字节,文件操作)
    python第六天(元组、字典、集合)
    python第五天
    python第四天
    根据数据库文件,查找对应的数据库
    Windows 路径问题
    32位及64位操作系统的程序问题
    好玩的获取目录信息的例子[C#]
    C# 反射相关的东西
  • 原文地址:https://www.cnblogs.com/allanliu/p/4476019.html
Copyright © 2020-2023  润新知