将地理位置从Swift 2 ViewController传递给Javascript方法

苹果破碎机

下面的代码能够获取地理位置并将其打印出来。我是根据一些在线教程并查看Swift文档而得到的。我想将字符串形式的地理位置从Swift 2传递给Javascript。我能够获取GeoLocations,但我不知道如何将这些字符串传递给Webview中的Javascript代码。

以下是我拥有的代码:

@IBOutlet weak var Webview: UIWebView!

let locMgr = CLLocationManager()

override func viewDidLoad() {

    super.viewDidLoad()
    loadAddressURL()
    locMgr.desiredAccuracy = kCLLocationAccuracyBest
    locMgr.requestWhenInUseAuthorization()
    locMgr.startUpdatingLocation()
    locMgr.delegate = self //necessary



}

func locationManager(manager: CLLocationManager , didUpdateLocations locations: [CLLocation]){
    let myCurrentLoc = locations[locations.count-1]
    var myCurrentLocLat:String = "\(myCurrentLoc.coordinate.latitude)"
    var myCurrentLocLon:String = "\(myCurrentLoc.coordinate.longitude)"

    print(myCurrentLocLat)
    print(myCurrentLocLon)

    //pass to javascript here by calling setIOSNativeAppLocation

}

我的网站上有使用这种方法的javascript:

function setIOSNativeAppLocation(lat , lon){

  nativeAppLat = lat;
  nativeAppLon = lon;
  alert(nativeAppLat);
  alert(nativeAppLon);

}

用以下解决方案查看了另一个问题,该问题标记为从Swift到Java传递变量

func sendSomething(stringToSend : String) {
    appController?.evaluateInJavaScriptContext({ (context) -> Void in

       //Get a reference to the "myJSFunction" method that you've implemented in JavaScript
       let myJSFunction = evaluation.objectForKeyedSubscript("myJSFunction")

       //Call your JavaScript method with an array of arguments
       myJSFunction.callWithArguments([stringToSend])

       }, completion: { (evaluated) -> Void in
          print("we have completed: \(evaluated)")
    })
}

但是,我没有appDelegate,我想直接从此视图进行这些更改。因此,我得到了“使用未解析的标识符appDelegate”。

博米·贾加尼(Bhoomi Jagani)

您必须实现UIWebview委托。应该在webviewDidFinishLoad之后调用Javascript函数。

override func viewDidLoad() {
     super.viewDidLoad()
     // Do any additional setup after loading the view, typically from a nib.
     let url = NSURL (string: URLSTRING);
     let requestObj = NSURLRequest(URL: url!);
webView.delegate = self
    webView.loadRequest(requestObj);
  }

    func webViewDidFinishLoad(webView: UIWebView) {
            let javaScriptStr = "setIOSNativeAppLocation(\(myCurrentLoc.coordinate.latitude), \(myCurrentLoc.coordinate.longitude))"

            webView.stringByEvaluatingJavaScriptFromString(javaScriptStr)
        }

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章