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

标签 ios swift uiwebview

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

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

如何将 url 哈希或搜索值设置为不加载

.../index.html

但例如:

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

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

最佳答案

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

在 Swift( native 代码)上,我创建了计时器监听 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);
        }
    }

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

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

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

或者您可以通过 JavaScript 检测:

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

现在你知道什么时候在你的原生 swift 代码中改变了角度路径 :D

关于ios - 如何在 Swift 中更改 WebView 的 URL 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33634509/

相关文章:

ios - 带有主机应用程序的 Xcode 测试目标强制错误的目标进入方案的构建部分

ios - swift 如何比较泛型

ios - 获取 UIWebView 网址! (myWebView.request.URL.absoluteString 不工作)

iphone - UIWebView - 如何识别 "last"webViewDidFinishLoad 消息?

ios - ITMS-90809 : Deprecated API Usage -- Apple will stop accepting submissions of apps that use UIWebView APIs

ios - 在 iOS 中解析连续的 JSON 流

ios - 根据缩放级别缩放自定义标记图标

c# - 如何在没有 IDE 的情况下使用 Xamarin?

swift - 在拖放之间丢失 NSAttributedString 的属性

ios - Swift UIlabels 在 uistackview 中显示不正确