app*_*her 6 javascript uiwebview ios swift
下面的代码能够获取地理位置并将其打印出来.我基于一些在线教程并查看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
}
Run Code Online (Sandbox Code Playgroud)
我的网站上有这个方法的javascript:
function setIOSNativeAppLocation(lat , lon){
nativeAppLat = lat;
nativeAppLon = lon;
alert(nativeAppLat);
alert(nativeAppLon);
}
Run Code Online (Sandbox Code Playgroud)
我已经查看了另一个标记为从Swift到Javascript的Pass变量的问题,其中包含以下解决方案:
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)")
})
}
Run Code Online (Sandbox Code Playgroud)
但是我没有appDelegate,我希望直接从这个视图中进行这些更改.所以我得到了"使用未解析的标识符appDelegate".
你必须实现UIWebview delegate.Javascript函数应该在webviewDidFinishLoad之后调用.
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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
476 次 |
| 最近记录: |