Egret白鹭引擎iOS使用WKWebView调起支付宝支付

一、引入头文件

#import <WebKit/WebKit.h>
/// 控件高度
#define kSearchBarH  44
#define kBottomViewH 44
/// 屏幕大小尺寸
#define kScreenWidth  [UIScreen mainScreen].bounds.size.width
#define kScreenHeight [UIScreen mainScreen].bounds.size.height
添加WKNavigationDelegate协议
@interface ViewController ()<CLLocationManagerDelegate, WKNavigationDelegate>
/// 网页控制导航栏
@property (weak, nonatomic) UIView *bottomView;
@property (nonatomic, strong) WKWebView *wkWebView;
@property (weak, nonatomic) UIButton *backBtn;

二、注册

[EgretWebViewLib setExternalInterface:@"callNativeForPay" Callback:^(NSString* msg) {
        NSLog(@"message: %@", msg);
        [self getPay:msg];
    }];

三、调起

- (void)getPay:(NSString*)jsonString {
    [self addSubViews];
    // 将json字符串转换成字典
    NSError * error = nil;
    NSData * getJsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary * getDict = [NSJSONSerialization JSONObjectWithData:getJsonData options:NSJSONReadingMutableContainers error:&error];
    NSString* payUrl = [getDict objectForKey:@"payUrl"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:payUrl]];
    NSArray *cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage].cookies;
    //Cookies数组转换为requestHeaderFields
    NSDictionary *requestHeaderFields = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
    //设置请求头
    request.allHTTPHeaderFields = requestHeaderFields;
    [self.wkWebView loadRequest:request];
//    [self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.cnblogs.com/mddblog/"]]];
}
- (void)addSubViews {
    [self addBottomViewButtons];
    
    [self.view addSubview:self.wkWebView];
}
- (void)addBottomViewButtons {
    // 记录按钮个数
    int count = 0;
    // 添加按钮
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    [button setTitle:@"关闭" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor colorWithRed:249 / 255.0 green:102 / 255.0 blue:129 / 255.0 alpha:1.0] forState:UIControlStateNormal];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateHighlighted];
    [button setTitleColor:[UIColor lightGrayColor] forState:UIControlStateDisabled];
    [button.titleLabel setFont:[UIFont systemFontOfSize:16]];
    button.tag = ++count;    // 标记按钮
    [button addTarget:self action:@selector(onBottomButtonsClicled:) forControlEvents:UIControlEventTouchUpInside];
    [self.bottomView addSubview:button];
    self.backBtn = button;
    // 统一设置frame
    [self setupBottomViewLayout];
}
- (void)setupBottomViewLayout
{
    int count = 1;
    CGFloat btnW = 80;
    CGFloat btnH = 30;
    
    CGFloat btnY = (self.bottomView.bounds.size.height - btnH) / 2;
    // 按钮间间隙
    CGFloat margin = (self.bottomView.bounds.size.width - btnW * count) / count;
    
    CGFloat btnX = margin * 0.5;
    self.backBtn.frame = CGRectMake(btnX, btnY, btnW, btnH);
}
/// 按钮点击事件
- (void)onBottomButtonsClicled:(UIButton *)sender {
    NSLog(@"关闭");
    _wkWebView.hidden = YES;
    self.bottomView.hidden = YES;
    [EgretWebViewLib callExternalInterface:@"callJSForPay" Value:@""];
}
#pragma mark - WKWebView WKNavigationDelegate 相关
/// 是否允许加载网页 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    NSString *urlString = [[navigationAction.request URL] absoluteString];
    NSLog(@"----->%@",urlString);
    urlString = [urlString stringByRemovingPercentEncoding];
    //    NSLog(@"urlString=%@",urlString);
    // 用://截取字符串
    NSArray *urlComps = [urlString componentsSeparatedByString:@"://"];
    if ([urlComps count]) {
        // 获取协议头
        NSString *protocolHead = [urlComps objectAtIndex:0];
        NSLog(@"protocolHead=%@",protocolHead);
    }
    
    if ([urlString containsString:@"alipays://"]) {
        NSLog(@"alipay");
        NSRange range = [urlString rangeOfString:@"alipays://"]; //截取的字符串起始位置
        NSString * resultStr = [urlString substringFromIndex:range.location]; //截取字符串
        
        NSURL *alipayURL = [NSURL URLWithString:resultStr];
        
        [[UIApplication sharedApplication] openURL:alipayURL options:@{UIApplicationOpenURLOptionUniversalLinksOnly: @NO} completionHandler:^(BOOL success) {
            NSLog(@"%d",success);
            if (success == false){
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"打开支付宝失败!请检查是否已经安装支付宝" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *actionConfirm = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alert addAction:actionConfirm];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    
}
#pragma mark - 懒加载
- (UIView *)bottomView {
    if (_bottomView == nil) {
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kBottomViewH, kScreenWidth, kBottomViewH)];
        view.backgroundColor = [UIColor colorWithRed:230/255.0 green:230/255.0 blue:230/255.0 alpha:1];
        [self.view addSubview:view];
        _bottomView = view;
    }
    return _bottomView;
}
- (WKWebView *)wkWebView {
    if (_wkWebView == nil) {
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight- kBottomViewH)];
        webView.navigationDelegate = self;
        //                webView.scrollView.scrollEnabled = NO;
        
        //        webView.backgroundColor = [UIColor colorWithPatternImage:self.image];
        // 允许左右划手势导航,默认允许
        webView.allowsBackForwardNavigationGestures = YES;
        _wkWebView = webView;
    }
    _wkWebView.hidden = NO;
    self.bottomView.hidden = NO;
    return _wkWebView;
}


发表评论

(必填)

(必填)

(以便回访)

博客已稳定运行: 访问量:191,782 views 网站备案号:闽ICP备17026396号-1