IOS UIWebView (API+JS交互)、WKWebView

来源:互联网 发布:用网络盒子看电视直播 编辑:程序博客网 时间:2024/05/19 22:06


javascriptCore.framework

使用如下代码可以等比缩放webview的网页大小,以便适配手机大小,0.5表示缩小为原网页1/2大小:- (void)webViewDidFinishLoad:(UIWebView *)webView  {      [webView stringByEvaluatingJavaScriptFromString:@"document.body.style.zoom=0.5"];  }  webView上下文JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];(1)获取页面titleNSString *title = [webview stringByEvaluatingJavaScriptFromString:@"document.title"];(2)获取当前的URLNSString *url = [webview stringByEvaluatingJavaScriptFromString:@"document.location.href"];



    WebView Post 请求 H5

 

NSURL *url = [NSURL URLWithString:self.url];    NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL: url];    [request setHTTPMethod: @"POST"];    [request setHTTPBody: [self.body dataUsingEncoding: NSUTF8StringEncoding]];    [self.webView loadRequest: request];


WebView使用

webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 100, CGRectGetWidth(self.view.frame), 500)];    webView.delegate = self;    [self.view addSubview:webView];            //设置URL请求    NSURL *url = [NSURL URLWithString:@"http://www.baidu.com"];    NSURLRequest *request = [NSURLRequest requestWithURL:url];            //请求事件    [webView loadRequest:request];                //@property (nonatomic) BOOL scalesPageToFit;    //自动适配屏幕    webView.scalesPageToFit = YES;            //禁止反弹    [(UIScrollView *)[[webView subviews] objectAtIndex:0] setBounces:NO];                    //@property (nonatomic) UIDataDetectorTypes dataDetectorTypes NS_AVAILABLE_IOS(3_0);    /*     typedef NS_OPTIONS(NSUInteger, UIDataDetectorTypes) {        UIDataDetectorTypePhoneNumber   = 1 << 0,          // 默认 电话号码        UIDataDetectorTypeLink          = 1 << 1,          // URL        #if __IPHONE_4_0 <= __IPHONE_OS_VERSION_MAX_ALLOWED        UIDataDetectorTypeAddress       = 1 << 2,          // Email地址        UIDataDetectorTypeCalendarEvent = 1 << 3,          // 日历 打开 ActionSheet             UIDataDetectorTypeNone          = 0,               // 无超链        UIDataDetectorTypeAll           = NSUIntegerMax    // All types     };     */    webView.dataDetectorTypes = UIDataDetectorTypeAll;                    //@property (nonatomic) BOOL allowsInlineMediaPlayback NS_AVAILABLE_IOS(4_0); // iPhone Safari defaults to NO. iPad Safari defaults to YES    //这个值决定了用内嵌HTML5播放视频还是用本地的全屏控制。(iPhone 默认关闭,iPad 默认打开)        webView.allowsInlineMediaPlayback = YES;                    //@property (nonatomic) BOOL mediaPlaybackRequiresUserAction NS_AVAILABLE_IOS(4_0); // iPhone and iPad Safari both default to YES    //在iPhone和iPad上默认使YES。这个值决定了HTML5视频可以自动播放还是需要用户去启动播放    webView.mediaPlaybackRequiresUserAction = NO;                    //@property (nonatomic) BOOL mediaPlaybackAllowsAirPlay NS_AVAILABLE_IOS(5_0); // iPhone and iPad Safari both default to YES    //这个值决定了从这个页面是否可以Air Play(蓝牙)。 在iPhone和iPad上默认使YES。    webView.mediaPlaybackAllowsAirPlay = YES;                    //@property (nonatomic) BOOL suppressesIncrementalRendering NS_AVAILABLE_IOS(6_0); // iPhone and iPad Safari both default to NO    //是否网页内容下载完毕才开始渲染web视图,默认为NO    webView.suppressesIncrementalRendering = NO;                    //@property (nonatomic) BOOL keyboardDisplayRequiresUserAction NS_AVAILABLE_IOS(6_0); // default is YES    //是否在web页面响应用户输入弹出键盘,默认为YES    webView.keyboardDisplayRequiresUserAction  = YES;                    //===================以下是io7新特性======================        //@property (nonatomic) UIWebPaginationMode paginationMode NS_AVAILABLE_IOS(7_0);    //设置此项属性网页会压缩展示,当网页的大小超出view时,以翻页的效果展示    /**        typedef NS_ENUM(NSInteger, UIWebPaginationMode) {            UIWebPaginationModeUnpaginated,//不使用翻页效果            UIWebPaginationModeLeftToRight,//将网页超出部分分页,从左向右进行翻页            UIWebPaginationModeTopToBottom,//将网页超出部分分页,从上向下进行翻页            UIWebPaginationModeBottomToTop,//将网页超出部分分页,从下向上进行翻页            UIWebPaginationModeRightToLeft//将网页超出部分分页,从右向左进行翻页    };    */        webView.paginationMode = UIWebPaginationModeTopToBottom;                        //@property (nonatomic) UIWebPaginationBreakingMode paginationBreakingMode NS_AVAILABLE_IOS(7_0);    //webView加载页面具有CSS属性时是使用页的样式还是以列的样式。    /**        typedef NS_ENUM(NSInteger, UIWebPaginationBreakingMode) {            UIWebPaginationBreakingModePage,            UIWebPaginationBreakingModeColumn     };     */    webView.paginationBreakingMode = UIWebPaginationBreakingModeColumn;                    //@property (nonatomic) CGFloat pageLength NS_AVAILABLE_IOS(7_0);    //分页的长度    webView.pageLength = 50;            //@property (nonatomic) CGFloat gapBetweenPages NS_AVAILABLE_IOS(7_0);    //页面之间间距    webView.gapBetweenPages = 1;                //@property (nonatomic, readonly) NSUInteger pageCount NS_AVAILABLE_IOS(7_0);    //分页数    NSUInteger count = webView.pageCount;


取消侧边和底部滚动条

UIWebView * d_intro = [[UIWebView alloc] init];d_intro.delegate = self;d_intro.dataDetectorTypes = UIDataDetectorTypeLink;    //取消右侧,下侧滚动条,去处上下滚动边界的黑色背景    d_intro.backgroundColor=[UIColor clearColor];     for (UIView *_aView in [d_intro subviews])      {         if ([_aView isKindOfClass:[UIScrollView class]])          {             [(UIScrollView *)_aView setShowsVerticalScrollIndicator:NO];             //右侧的滚动条             [(UIScrollView *)_aView setShowsHorizontalScrollIndicator:NO];             //下侧的滚动条                         for (UIView *_inScrollview in _aView.subviews)              {                 if ([_inScrollview isKindOfClass:[UIImageView class]])                 {                     _inScrollview.hidden = YES;  //上下滚动出边界时的黑色的图片                 }             }         }     }        [self.view addSubview:d_intro];



JS调用OC方法

转自:http://www.2cto.com/kf/201503/383795.html

一、以前使用js调用object-c的方法

关于如何使用javascript调用object-c中的函数和方法,我搜索了好久

网上所有的方法,基本都指明了一个方向,那就是在UIWebview中载入的js代码中

通过改变document.locations=“”,然后回调UIWebview的

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType

函数,在上面这个函数中,通过截取NSURLRequest解析js中传递过来的参数,再根据参数

来选择早已定义好的方法。

有没有别的方法呢? 我找了几个月,没找到!但是有一个转机。

 

我偶然知道了 javascriptCore.framework 这个库

于是事情有了转机。

 

二、在js中直接调用oc的方法

 

废话不多说,现在看看如何在UIWebView的javascript中调用oc的方法

 

 

首先在建立一个UIWebView,代码如下:

////  webview.m//  login////  Created by wangdan on 15-3-19.//  Copyright (c) 2015年 wangdan. All rights reserved.//#import "webview.h"#import @implementation webview-(id)initWithFrame:(CGRect)frame{    self=[super initWithFrame:frame];        if( self ){        self.webview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 310, self.bounds.size.width, 300)];        self.webview.backgroundColor=[UIColor lightGrayColor];        NSString *htmlPath=[[NSBundle mainBundle] resourcePath];        htmlPath=[htmlPath stringByAppendingPathComponent:@"html/index.html"];        NSURL *localURL=[[NSURL alloc]initFileURLWithPath:htmlPath];        [self.webview loadRequest:[NSURLRequest requestWithURL:localURL]];        [self addSubview:self.webview];         JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];         context[@"log"] = ^() {            NSLog(@"+++++++Begin Log+++++++");            NSArray *args = [JSContext currentArguments];            for (JSValue *jsVal in args) {                NSLog(@"%@", jsVal);            }            JSValue *this = [JSContext currentThis];            NSLog(@"this: %@",this);            NSLog(@"-------End Log-------");        };        //        [context evaluateScript:@"log('ider', [7, 21], { hello:'world', js:100 });"];            }    return self;}@end

 

(1)在上述代码中,使用javascriptCore.framework,首先使用UIWebview加载一个静态网页,并

使用

JSContext *context = [self.webview valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];

获取该UIWebview的javascript执行环境。

 

 

(2)在该javascript执行环境中,定义一个js函数,注意关键点来了

 

这个函数的执行体完全是 objective-c代码写的,也就是下面:

    context[@"jakilllog"] = ^() {            NSLog(@"Begin Log");            NSArray *args = [JSContext currentArguments];            for (JSValue *jsVal in args) {                NSLog(@"%@", jsVal);            }            JSValue *this = [JSContext currentThis];            NSLog(@"-------End Log-------");        };
 
 

(3)试想一下,在定义的webview中,如果使用js执行log这个函数,那么会不会调用上面oc中block段代码呢,答案是肯定的!

下面看看UIWebView 中所加载的 html及其js代码是如何写的

(4)index.html代码

 

<script type="text/javascript" src="index.js"></script>
上面html定义了一个button,然后引用index.js,点击button的响应函数为buttonClick()
该函数在index.js中定义,如下
function buttonClick(){jakilllog("hello world");}

意思是点击这个button,就调用jakilllog()函数,jakilllog()函数显然是我们在oc中实现的一个block段,

就是上述绿色部分的block段。

 

点击button会执行么?答案是肯定的。

下面上图\

 

下图是执行的结果

\

UIWebView登陆需要记住用户名和密码下次自动登陆。(iOS UIWebView 通过 cookie 完成自动登录。)

现在我有个APP是嵌入的webView 登陆需要记住用户名和密码下次自动登陆,求大神看看如何实现?谢谢
目前这个问题我已经解决了,希望有用到的朋友来这里看http://www.jianshu.com/p/7b7fb2c9c780:给颗心
另我把代码写到这里一份也:
1、在UIWebView的代理方法中实现获取cookies并将cookies放到NSUserDefaults保存起来

  • (void)webViewDidFinishLoad:(UIWebView*)webView{
    NSArray*nCookies = [[NSHTTPCookieStoragesharedHTTPCookieStorage]cookies];
    NSHTTPCookie*cookie;
    for(idcinnCookies)
    {
    if([cisKindOfClass:[NSHTTPCookieclass]])
    {
    cookie=(NSHTTPCookie*)c;
    if([cookie.nameisEqualToString:@"PHPSESSID"]) {
    NSNumber*sessionOnly = [NSNumbernumberWithBool:cookie.sessionOnly];
    NSNumber*isSecure = [NSNumbernumberWithBool:cookie.isSecure];
    NSArray*cookies = [NSArrayarrayWithObjects:cookie.name, cookie.value, sessionOnly, cookie.domain, cookie.path, isSecure,nil];
    [[NSUserDefaultsstandardUserDefaults]setObject:cookiesforKey:@"cookies"];
    break;
    }
    }
    }
    }

2、获取cookies:运行之后,UIWebview加载url之前获取保存好的cookies,并设置cookies,

NSArray*cookies =[[NSUserDefaultsstandardUserDefaults]objectForKey:@"cookies"];NSMutableDictionary*cookieProperties = [NSMutableDictionarydictionary];[cookiePropertiessetObject:[cookiesobjectAtIndex:0]forKey:NSHTTPCookieName];[cookiePropertiessetObject:[cookiesobjectAtIndex:1]forKey:NSHTTPCookieValue];[cookiePropertiessetObject:[cookiesobjectAtIndex:3]forKey:NSHTTPCookieDomain];[cookiePropertiessetObject:[cookiesobjectAtIndex:4]forKey:NSHTTPCookiePath];NSHTTPCookie*cookieuser = [NSHTTPCookiecookieWithProperties:cookieProperties];[[NSHTTPCookieStoragesharedHTTPCookieStorage]setCookie:cookieuser];

注意:要在[self.webView loadRequest:req];之前设置获取cookies!



如何让 UIWebView 能通过“捏合”手势进行缩放?


webview=[[UIWebView alloc]init];    webview.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);    webview.scalesPageToFit=YES;    webview.multipleTouchEnabled=YES;    webview.userInteractionEnabled=YES;




uiwebview设置超时的问题
   

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:URL]                                                      cachePolicy:NSURLRequestReloadIgnoringLocalCacheData                                                  timeoutInterval:60];        [webview loadRequest:request];-(void)refresh:(id)sender{    NSLog(@"in refresh");    if (self.webView.loading) {        [self.webView stopLoading];    }    //发生错误时则重新加载主页    if (hasError) {        [self.webView loadRequest:mainRequest];    }else{        [self.webView reload];    }  - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{    [self activeBtns];    mainRequest.URL = request.URL;} }


用NSURLCache解决UIWebView请求远程资源慢的问题




WebView 如何通过js获取网页中所有图片并加入点击事件,实现浏览图片的功能

转自:http://blog.csdn.net/u014544904/article/details/50479083

在网页加载完成时,通过js获取图片和添加点击的识别方式

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

    [IDProgressHUD IDPlaceViewHideDirect:self.view];

    

    //这里是js,主要目的实现对url的获取

    static  NSString * const jsGetImages =

    @"function getImages(){\

    var objs = document.getElementsByTagName(\"img\");\

    var imgScr = '';\

    for(var i=0;i<objs.length;i++){\

    imgScr = imgScr + objs[i].src + '+';\

    };\

    return imgScr;\

    };";

    

    [webView stringByEvaluatingJavaScriptFromString:jsGetImages];//注入js方法

    NSString *urlResurlt = [webView stringByEvaluatingJavaScriptFromString:@"getImages()"];

    mUrlArray = [NSMutableArray arrayWithArray:[urlResurlt componentsSeparatedByString:@"+"]];

    if (mUrlArray.count >= 2) {

        [mUrlArray removeLastObject];

    }

    //urlResurlt 就是获取到得所有图片的url的拼接;mUrlArray就是所有Url的数组

    

    //添加图片可点击js

    [mWebView stringByEvaluatingJavaScriptFromString:@"function registerImageClickAction(){\

     var imgs=document.getElementsByTagName('img');\

     var length=imgs.length;\

     for(var i=0;i<length;i++){\

     img=imgs[i];\

     img.onclick=function(){\

     window.location.href='image-preview:'+this.src}\

     }\

     }"];

    [mWebView stringByEvaluatingJavaScriptFromString:@"registerImageClickAction();"];

}


//在这个方法中捕获到图片的点击事件和被点击图片的url

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {

    

    //预览图片

    if ([request.URL.scheme isEqualToString:@"image-preview"]) {

        NSString* path = [request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];

        path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

        //path 就是被点击图片的url

        return NO;

    }

    return YES;

}



修改 user-agent
目的:用于浏览器判断

+(void)userAgent{    //修改app默认UA    @autoreleasepool {        UIWebView* tempWebView = [[UIWebView alloc] initWithFrame:CGRectZero];        NSString* userAgent = [tempWebView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];        //        NSLog(@"------%@",userAgent);        NSString *executableFile =@"mplay";        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:(NSString *)kCFBundleVersionKey];        NSString *ua = [NSString stringWithFormat:@"%@ %@/%@",                        userAgent,                        executableFile,version];        //        NSLog(@"------%@",ua);                [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent" : ua, @"User-Agent" : ua}];#if !__has_feature(objc_arc)        [tempWebView release];#endif    }}


Cookies

通常添加Token给Web、UIWebView和WKWebView的添加方法(第一种用PHP测试和本地不成功,最后只能Request时候修改)

参考:http://blog.csdn.net/qq_30513483/article/details/51798692



0 0