IOS UIWebView与JavaScript交互实现Web App

来源:互联网 发布:搬瓦工 不适合 建站 编辑:程序博客网 时间:2024/05/18 22:17

上一篇文章讲到了Android WebView与JavaScript的交互问题,现在来讲一下IOS的UIWebView与JavaScript的交互问题。和Android的相比,IOS的会略显笨拙一些不大友好,然而也算是在未引用第三方框架的基础上完成了交互的问题。OK,现在开始吧。

1.首先在IOSA->Application下选择Single View Application创建一个IOS应用,命名为JSInteraction,然后我删去了Info.plist文件里Main storyboard file base name字段,选择加载ViewController的View。

 

1.修改AppDelegate.m的didFinishLaunchingWithOptions并添加如下代码。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    // Override point for customization after application launch.        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];    [self.window makeKeyAndVisible];        ViewController * viewController = [[ViewController alloc] init];    [self.window setRootViewController:viewController];        return YES;}
2.修改类ViewController,添加一个WebView并添加与JavaScript交互的功能。

////  ViewController.h//  JSInteraction////  Created by Winter on 15/8/12.//  Copyright (c) 2015年 YLD. All rights reserved.//#import <UIKit/UIKit.h>@interface ViewController : UIViewController<UIWebViewDelegate> {    UINavigationItem *item_;}@property (nonatomic, strong) UIWebView *webView;@end

在WebView的shouldStartLoadWithRequest处理JS的请求根据JS的传入的Url来判断JS所需的操作。在这里面我主要提供了一个弹出对话框的接口,当JS传入的URL是以jsinteraction:showAleart开头时则调用ViewController里的showAlert方法,而JS需要从App获取数据时,则需要WebView调用stringByEvaluatingJavaScriptFromString方法并传入后台JS提供的方法并传入参数来实现传递数据给后台的JS。有点绕,且看看实现方式。

////  ViewController.m//  JSInteraction////  Created by Winter on 15/8/12.//  Copyright (c) 2015年 YLD. All rights reserved.//#import "ViewController.h"@interface ViewController ()@end@implementation ViewController- (void)viewDidLoad {    [super viewDidLoad];        UINavigationBar *bar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 20, self.view.bounds.size.width, 30.0f)];    bar.backgroundColor = [UIColor clearColor];    item_ = [[UINavigationItem alloc] initWithTitle:@""];    [bar pushNavigationItem:item_ animated:YES];    [self.view addSubview:bar];        self.view.backgroundColor = [UIColor colorWithRed:0.0f green:20.0f blue:255.0f alpha:1.0f];    self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(10.0f, 60.0f, self.view.bounds.size.width-20, self.view.bounds.size.height - 80.0f)];    self.webView.delegate = self;    [self.view addSubview:self.webView];            [self initializeWebView];        // Do any additional setup after loading the view, typically from a nib.}- (void)didReceiveMemoryWarning {    [super didReceiveMemoryWarning];    // Dispose of any resources that can be recreated.}/* * Load local html file */- (void)initializeWebView {    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"LoginJs/login" ofType:@"html"];        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:filePath]]];}- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {    NSString *requestString = [[request URL] absoluteString];    NSArray *headers = [requestString componentsSeparatedByString:@":"];    if([headers count]>1) {        NSString *appAction = [(NSString *)[headers objectAtIndex:0] lowercaseString];        NSString *funtionName =(NSString*)[headers objectAtIndex:1];                if([appAction isEqualToString:@"jsinteraction"]) {            if([funtionName isEqualToString:@"showAleart"] && [headers count] > 2){                NSString* message = (NSString*)[headers objectAtIndex:2];                            [self showAleart:message];            }                    return NO;        } else if([appAction isEqualToString:@"executescript"]){            if([funtionName isEqualToString:@"loginObj.setLoginInfo"]){                NSString *loginInfo = @"'{\"Username\":\"YLD\",\"Password\":\"111\"}'";                NSString *execute = [NSString stringWithFormat:@"loginObj.setLoginInfo(%@)", loginInfo];                            [webView stringByEvaluatingJavaScriptFromString:execute];            }            return NO;        }    }        return YES;}- (void)webViewDidFinishLoad:(UIWebView *)webView {    item_.title = [self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];}/** * 弹出消息对话框 */- (void)showAleart: (NSString *) message {    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Warning"                                                        message:message                                                       delegate:self                                              cancelButtonTitle:@"OK"                                              otherButtonTitles:nil , nil];        [alertView show];}@end

3.IOS端已经完成,根据目前的实现,JS端需要请求的URL须是以下两种格式才能实现与IOS的交互。

1)jsinteraction:showAleart:xxxx

2)  executescript:loginObj.setLoginInfo:xxxx

4.下面实现web端的功能,新建一个文件夹命名为LoginJs,在改文件夹下添加两个文件,login.html和login.js。login.html有两个文本输入框我们会在程序启动时让IOS端为其注入相应的数据,再有一个登录按钮,点击按钮则会调用IOS端ViewController的showAlert方法,弹出对话框。

<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title id="title">Login</title><script type="text/javascript" src="login.js"></script></head><body style="background:lightblue"><div style="margin-top: 20px;margin-left: 20px"><div><label>Username:</label><input id="txtUsername" type="text" style="margin-left: 20px"/></div><div style="margin-top: 20px"><label>Password:</label><input id="txtPassword" type="text" style="margin-left: 20px"/></div><div style="margin-top: 20px;margin-left: 160px"><button onclick="loginObj.login()" style="width:100px">Login</button></div></div></body></html>
在login.js中实现相应的方法,在页面加载完成时会调用请求,请求IOS端的数据。实现与IOS端的交互主要是依靠更改window的location。

"user strict"var Login = (function(){function Login(){}Login.prototype.login = function(){this.appRequest("JSInteraction", "showAleart", "Start...");}    /**     * 设置登录信息     * @logininfoJson json参数字符串     */Login.prototype.setLoginInfo = function(logininfoJson){//解析json字符串        var logininfo = eval("("+logininfoJson+")");document.getElementById("txtUsername").value = logininfo.Username;document.getElementById("txtPassword").value = logininfo.Password;}    Login.prototype.appRequest = function(appAction, functionName, parameters){        var requestCommand = appAction + ":" + functionName + ":" + parameters;        window.location = requestCommand;    }             return Login;})();var loginObj = new Login();window.onload=function(){    loginObj.appRequest("executeScript", "loginObj.setLoginInfo", "");}

5.接下来我们将web的LoginJs添加至IOS的JSInteraction工程中



添加完成后,工程结构如下图


6.运行App,效果如下所示。


点击Login按钮



源代码下载页:http://download.csdn.net/detail/leyyang/9000543

4 0
原创粉丝点击