如何在Swift中更改WebView的URL哈希

时间:2015-11-10 16:13:35

标签: ios swift uiwebview

我确实将本地单页webapp加载到iOS UIWebView中。 html文件通过

加载
var prefix = useLighting ? '#define USE_TEXTURE' : '';
var shaderSource = prefix + originalShaderSource;

如何将url hash或search值设置为不加载

    let url = NSBundle.mainBundle().URLForResource("index", withExtension:"html", subdirectory: "html")
    let requestObj = NSURLRequest(URL: url!);

但是例如:

.../index.html

加载html文件后,我能以某种方式更改哈希值或搜索值吗?

1 个答案:

答案 0 :(得分:1)

嘿,我用这段代码解决了我的问题:

在Swift(本机代码)上我创建了定时器监听javascript变量:

   override func viewDidLoad() {
         super.viewDidLoad()
         ...
         var timer = NSTimer.scheduledTimerWithTimeInterval(
                  0.4,
                  target: self,
                  selector: #selector(ViewController.update), //#call method
                  userInfo: nil,
                  repeats: true)

使用此方法(#call方法)来监听javascript变量:

   var pathCurrent: String!;    
   func update() {

       let path: String! = webView.stringByEvaluatingJavaScriptFromString("var path = public.path;  (function(_path){return _path;})(path)")

        if (path != pathCurrent)
        {
            //path changed
            print(path);

            pathCurrent = path;
        }

            print(path);
        }
    }

注意,这段代码,读取公共变量 - > var path = public.path;

现在,在Angular JS中,您可以在路由更改时更改公共变量:

$scope.$on("$routeChangeSuccess", function($currentRoute, $previousRoute) {
     public.path = $location.$$path;    
});

或者您可以通过JavaScript检测到:

window.onhashchange = function() {  
    public.path = location.href.substr(path.indexOf("#/")+1);
}

现在您知道在您的原生swift代码中更改角度路径时:D