標籤:ios javascript html 互動 uiwebview
上一篇文章講到了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
著作權聲明:本文為博主原創文章,轉載時須註明本文的詳細連結,否則作者將保留追究其法律責任。
IOS UIWebView與JavaScript互動實現Web App