标签:int java 包含 load 重写 his 选中 apple 技术
var script = document.createElement(‘script‘);
script.type = ‘text/javascript‘;
script.text = ‘
function signin_go(){
location.href="ios:@signin_go";
}
‘;
document.getElementsByTagName(‘head‘)[0].appendChild(script);
//
// ViewController.swift
// Swift_UIWebView
//
// Created by 周文春 on 16/3/1.
// Copyright ? 2016年 周文春. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UIWebViewDelegate {
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
//加载网页
webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://passport.cnblogs.com/user/signin")!))
webView.delegate = self
}
//webView代理方法,链接地址发生改变的时候调用
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool{
//获取链接的地址
let rurl = request.URL?.absoluteString
//判断链接的前缀,是都包含ios:,就相当于OC中的判断网页跳转一样
if (rurl!.hasPrefix("ios:")){
//判断之后,因为js脚本里面链接是以@连接的location.href="ios:@signin_go"所以这里我们将链接进行分割之后取到后面的signin_go方法,用来调用我们重写OC中的方法
let method = rurl!.componentsSeparatedByString("@")[1]
if method == "signin_go"{
signin_go()
}
return false
}
return true
}
//webView代理方法,网页内容加载完成时调用
func webViewDidFinishLoad(webView: UIWebView){
/**
注入脚本
*/
//获取我们名为app.js的脚本路径
let jsPath = NSBundle.mainBundle().pathForResource("app", ofType: "js")
//获取到脚本中的内容
var jsString :String = try! String(contentsOfFile: jsPath!, encoding: 4)
//将获得的文本内容后面的\n替换为空的字符串
jsString = jsString.stringByReplacingOccurrencesOfString("\n", withString: "")
//触发脚本
webView.stringByEvaluatingJavaScriptFromString(jsString as String)
}
func signin_go(){
NSLog("JS 调用了OC中的signin_go方法")
// //通过以下方法可以获得用户名或者密码等;
// var userName = webView.stringByEvaluatingJavaScriptFromString("脚本")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
解决方法: 在前面加上try! ;
//获取到脚本中的内容
var jsString :String = try! String(contentsOfFile: jsPath!, encoding: 4)
2016-03-01 13:21:31.860 Swift_UIWebView[2292:905421] Incorrect NSStringEncoding value 0x0000 detected. Assuming NSASCIIStringEncoding. Will stop this compatiblity mapping behavior in the near future.
解决方法:将encoding值设置为4,设置UTF8的编码格式即可;
参考:http://www.cnblogs.com/wuxian/p/4470634.html
标签:int java 包含 load 重写 his 选中 apple 技术
原文地址:http://www.cnblogs.com/Free-Thinker/p/7115318.html