iOS中WebView的一些使用

返回按钮

在web页面中,可能存在多级跳转的问题,但是默认的返回按钮会返回原生页面的上级页面,这个时候,我们通常需要做一下处理(代码:)

if ([_mainWebView canGoBack]) {//判断是否存在web页面的返回
            [_mainWebView goBack];
            //用延迟处理的方式刷新webview(非延迟刷新会出现一些问题)
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [_mainWebView reload];
            });

web页面和js的交互:

web页面和js有三种交互方式,协议交互,链接交互和代理交互,协议交互和链接交互其实可以看做是一个东西都是在- (BOOL)webView:(UIWebView )webView shouldStartLoadWithRequest:(NSURLRequest )request navigationType:(UIWebViewNavigationType)navigationType这个方法里面进行处理
例如:

NSString *requestString = [[request URL] absoluteString];
    NSLog(@"requestString = %@",requestString);

    if ([requestString rangeOfString:@"/account"].location != NSNotFound){
        [self.navigationController popViewControllerAnimated:YES];
    }

都是判断连接中是否含有某段特殊字符,然后进行对应的操作

但是往往实际操作过程中,我们会使用到更多的东西,比如说,在现有的很多项目的积分商城中,涉及到的登录问题,如何使用js调用登录,并且在登录之后跳转到对应的web页面,以及传递参数

这个时候我们就要使用代理的方式进行交互,例如:

@protocol JSObjcDelegate <JSExport>
//定义一个交互方法
- (void)jsMakeAppLogIn:(NSString *)urlString;
@end

在下面这个方法里面做处理


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

    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    NSLog(@"%@",context);
    context.exceptionHandler = ^(JSContext *con, JSValue *exception) {
        NSLog(@"%@", exception);
        con.exception = exception;
    };

    //h5里面的代码格式为xx.xxxx(xx为前缀,xxxx为方法名)
    context[@"前缀"] = self;
    context[@"方法名"] = ^{

        NSArray *arg = [JSContext currentArguments];
        for (id obj in arg) {
            NSLog(@"参数 === %@", obj);
            _getUrlValue = [NSString stringWithFormat:@"%@",obj];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self jsMakeAppLogIn:_getUrlValue];
        });
    };

}

web页面的缓存清理

清理缓存和cookie代码

- (void)cleanCacheAndCookie{
    //清除cookies
    NSHTTPCookie *cookie;
    NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    for (cookie in [storage cookies]){
        [storage deleteCookie:cookie];
    }
    //清除UIWebView的缓存
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    NSURLCache * cache = [NSURLCache sharedURLCache];
    [cache removeAllCachedResponses];
    [cache setDiskCapacity:0];
    [cache setMemoryCapacity:0];
}

打开webview的方式

web页面的打开同样分为POST打开和Get打开方式
关于Get的打开方式就不介绍了,主要介绍一下POST打开方式

        [_mainWebView loadRequest:[self openUrlWithPostMethod:_urlStr params:_paraDic]];

//POST方法编码URL和参数
- (NSMutableURLRequest *)openUrlWithPostMethod:(NSString*)url params:(NSDictionary*)params
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]];
    request.HTTPMethod = @"POST";
    NSMutableString *paramStr = [NSMutableString string];
    [params enumerateKeysAndObjectsUsingBlock:^( id key , id value , BOOL *stop ) {

        if( paramStr.length > 0 ){
            [paramStr appendString:@"&"];
        }
        if ([key isEqualToString:@"url"]) {

        }else
        [paramStr appendFormat:@"%@=%@",[self encodeString:key],[self encodeString:value]];
        *stop = NO;
    }];

    NSLog(@"%@  params ==== %@",request.URL,params);
    request.HTTPBody = [paramStr dataUsingEncoding:NSUTF8StringEncoding];

    return request;
}
-(NSString*)encodeString:(NSString*)unencodedString{
    NSString *encodedString = (NSString *)
    CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault,
                                                              (CFStringRef)unencodedString,
                                                              NULL,
                                                              (CFStringRef)@"!*'();:@&=+$,/?%#[]",
                                                              kCFStringEncodingUTF8));

    return encodedString;
}

web页面的App浏览器标记

-(void)setUserAgentForMyApp
{

    UIWebView* webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString* secretAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    NSString *newUagent = [NSString stringWithFormat:@"%@/特殊标记字段",secretAgent];
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newUagent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    webView = nil;
}

web页面的放大缩小(捏合手势)

    _mainWebView.autoresizingMask = (UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);

        _mainWebView.scalesPageToFit=YES;

        _mainWebView.multipleTouchEnabled=YES;

暂时先介绍这些具有代表性的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值