Search code examples
iosswiftuiwebview

How to change URL hash of WebView in Swift


I did load a local single page webapp into a iOS UIWebView. The html file is loaded via

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

How can I set the url hash or search value to not load just

.../index.html

but for example:

.../index.html?flag=test#main

Once the html file is loaded, can I change the hash or search value somehow?


Solution

  • Hey i resolve my problem with this code:

    On Swift (Native Code) i created the timer listen javascript variable change:

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

    Use this method (#call method) to listen the javascript variable:

       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);
            }
        }
    

    Note, this code, read the public variable -> var path = public.path;

    Now, in Angular JS, you can change the public variable when route was changed:

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

    Or you can detect via JavaScript:

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

    now you know when angular path was changed in your native swift code :D