有一個解決方案。 Google Maps API使用Cocoa框架類CLLocationManager。每個人如何獲得有關當前GPS位置更改的信息都必須符合CLLocationManagerDelegate併成爲CLLocationManager對象的代表。通過 locationManager:didUpdateLocations:delegate方法將更新發送到委託對象。 這是每個人都知道的理論。所以爲了模擬位置數據,我們需要找到一種方法來調用這個方法,將我們自己的數據傳遞給它。 幸運的是動態改變任何類的行爲的機會,通過功能class_addMethod和class_replaceMethod。所以,現在我們可以改變的方法override_abc的方法ABC可以在一個類中實現像這樣實施:
let originalSelector = NSSelectorFromString("setDelegate:")
let newSelector = NSSelectorFromString("override_setDelegate:")
let originalMethod = class_getInstanceMethod(CLLocationManager.self, originalSelector)
let newMethod = class_getInstanceMethod(CLLocationManager.self, newSelector)
method_exchangeImplementations(originalMethod, newMethod)
對於我們而言,我們需要改變二傳手的位置,管理者代表,加入我們自己的二傳手作爲擴展:
extension CLLocationManager {
func override_setDelegate(delegate: CLLocationManagerDelegate) {
// save a reference to self
GMLocationManager = self
override_setDelegate(delegate)
}
}
一旦我們已經保存在谷歌地圖位置管理器,我們現在可以調用的LocationManager的引用:使用一個額外的擴展方法simulateLocation委託方法:didUpdateLocations。
extension CLLocationManager {
func simulateLocation(location: CLLocation) {
self.delegate?.locationManager?(self, didUpdateLocations: [location])
}
}
// ...
GMLocationManager?.simulateLocation(fakeLocation)
'CLLocationManager'與'LocationSource'不同,它會在用戶位置或標題更改時更新數據。 – ztan