Unity2018接入第四方支付,采用WKWebView

unity跳转ios的webview,UnityAppController.mm

// 跳转方法
- (void)openBrower:(NSNotification *)notification
{
    NSString* strHtml = [notification.userInfo objectForKey:@"text"];
    BrowserViewController *browController = [[BrowserViewController alloc]init];
    browController.strHtml = strHtml;
    GetAppController().window.rootViewController = browController;
}
// 启动
- (BOOL)application:(UIApplication*)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions
{
    //增加一个通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(openBrower:) name:@"OpenBrower" object:nil];
    return YES;
}
打开浏览器网页
NSString *base64String = [childdic valueForKey:@"strMessage"] ;
NSData *data = [[NSData alloc]initWithBase64EncodedString:base64String options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *stringHtml = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
[[NSNotificationCenter defaultCenter] postNotificationName:@"OpenBrower" object:nil userInfo:@{@"text":stringHtml}];

ios的webview跳转到unity

BrowserViewController.h

//
//  BrowserViewController.h
//  Unity-iPhone
//
//  Created by chen on 2019/3/5.
//

#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN

@interface BrowserViewController : UIViewController<WKNavigationDelegate,WKUIDelegate,WKScriptMessageHandler>{
    UIView* _rootView;
    WKWebView *webView;
    
}
/** 属性传值参数 */
@property(nonatomic, strong)NSString *strHtml;

@property (nonatomic,  retain)IBOutlet UIView *_rootView;

- (IBAction) backGame:(id)sender;

@end

NS_ASSUME_NONNULL_END

BrowserViewController.m

//
//  BrowserViewController.m
//  Unity-iPhone
//
//  Created by chen on 2019/3/5.
//

#import "BrowserViewController.h"
#import "UnityAppController.h"
@interface BrowserViewController ()

@end

@implementation BrowserViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    //配置环境
//    WKWebViewConfiguration * config = [[WKWebViewConfiguration alloc]init];
//    config.preferences.javaScriptEnabled = YES;
    
    // 1.创建webview,并设置大小,"20"为状态栏高度
//    webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 50, self._rootView.frame.size.width, 1000) configuration:config];
    webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 50, self._rootView.frame.size.width, self._rootView.frame.size.height)];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;
    webView.scrollView.scrollEnabled = YES;
//    webView.scrollView.bounces = YES;
//    webView.scrollView.showsVerticalScrollIndicator = YES;
//    webView.scrollView.showsHorizontalScrollIndicator = YES;

    // 加载网页
    [webView loadHTMLString:self.strHtml baseURL:nil];
//    [config.userContentController addScriptMessageHandler:self name:@"closeWindow"];

    // 最后将webView添加到界面
    [self._rootView addSubview:webView];
    
}

- (IBAction) backGame:(id)sender{
    
    NSString* name = @"ThirdpartyManager";
    NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    [dictionary setValue:@1 forKey:@"Platformtype"];
    [dictionary setValue:@13 forKey:@"code"];
    [dictionary setValue:@"支付查询" forKey:@"msg"];
    
    //转成JSON
    NSError *error = nil;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionary
                                                       options:NSJSONWritingPrettyPrinted
                                                         error:&error];
    if (error)
    {
        NSLog(@"dic->%@",error);
    }
    
    NSString * jsonString  =[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    
    
    UnitySendMessage([name cStringUsingEncoding:NSUTF8StringEncoding],
                     "ThridToUnity",
                     [jsonString cStringUsingEncoding:NSUTF8StringEncoding]);
    
    NSLog(@"code:%@",jsonString);
    
    [webView stopLoading];
    [webView removeFromSuperview];
    webView = nil;
    [_rootView removeFromSuperview];
    _rootView = nil;
    GetAppController().window.rootViewController = UnityGetGLViewController();
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    return UIInterfaceOrientationMaskPortrait;
}


- (BOOL)shouldAutorotate{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - WKNavigationDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    
}
// 在收到响应后,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    
    NSLog(@"%@",navigationResponse.response.URL.absoluteString);
    //允许跳转
    decisionHandler(WKNavigationResponsePolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationResponsePolicyCancel);
}
// 在发送请求之前,决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    NSLog(@"%@",navigationAction.request.URL.absoluteString);
    //允许跳转
    //    decisionHandler(WKNavigationActionPolicyAllow);
    //不允许跳转
    //decisionHandler(WKNavigationActionPolicyCancel);
    
    NSString *requestUrl = navigationAction.request.URL.absoluteString;
    //  则跳转到本地支付宝App
    if ([requestUrl hasPrefix:@"alipays://"] || [requestUrl hasPrefix:@"alipay://"]) {
        // 跳转支付宝App
        BOOL isSucc = [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        if (!isSucc) {
            NSLog(@"用户未安装支付宝客户端");
        }
        return decisionHandler(WKNavigationActionPolicyCancel);
    }
    decisionHandler(WKNavigationActionPolicyAllow);
    
    
}

#pragma mark - WKUIDelegate
// 创建一个新的WebView
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    return [[WKWebView alloc]init];
}
// 输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler{
    completionHandler(@"http");
}
// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler{
    completionHandler(YES);
}
// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"%@",message);
    completionHandler();
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
}


- (void)dealloc
{
    [webView stopLoading];
    [webView removeFromSuperview];
    webView = nil;
}

@end

BrowserViewController.xib
里面的事件绑定就需要看下其他的blog了
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/mhtqq809201/article/details/88837419