【发布时间】:2016-07-11 22:34:27
【问题描述】:
下面的代码能够获取地理位置并将其打印出来。我是根据一些在线教程并查看 Swift Documents 得到的。我想以字符串的形式将地理位置从 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);
}
我查看了另一个标有Pass variable from Swift to Javascript 的问题,解决方案如下:
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”。
【问题讨论】:
-
只是一个模糊的想法...您可以在 webview 中启用本地存储然后设置它并稍后从 javascript 中读取它吗?
标签: javascript ios swift uiwebview