Skip to content

Instantly share code, notes, and snippets.

@manishkkatoch
Created December 6, 2017 17:51
Show Gist options
  • Save manishkkatoch/5886c41741349dadf64538d034e5dfcd to your computer and use it in GitHub Desktop.
Save manishkkatoch/5886c41741349dadf64538d034e5dfcd to your computer and use it in GitHub Desktop.
Swizzling CLLocationManager to use MockCLLocationManager
//
// CLLocationManager+Swizzle.swift
// mockLocation
//
// Created by Manich Katoch on 11/30/17.
// Copyright © 2017 mk. All rights reserved.
//
import Foundation
import MapKit
private let swizzling: (AnyClass, Selector, Selector) -> () = { forClass, originalSelector, swizzledSelector in
if let originalMethod = class_getInstanceMethod(forClass, originalSelector),
let swizzledMethod = class_getInstanceMethod(forClass, swizzledSelector) {
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
extension CLLocationManager {
static let classInit: Void = {
let originalSelector = #selector(CLLocationManager.startUpdatingLocation)
let swizzledSelector = #selector(swizzledStartLocation)
swizzling(CLLocationManager.self, originalSelector, swizzledSelector)
let originalStopSelector = #selector(CLLocationManager.stopUpdatingLocation)
let swizzledStopSelector = #selector(swizzledStopLocation)
swizzling(CLLocationManager.self, originalStopSelector, swizzledStopSelector)
}()
@objc func swizzledStartLocation() {
print("swizzled start location")
if !MockCLLocationManager.shared.isRunning {
MockCLLocationManager.shared.startMocks(usingGpx: "locationTrack")
}
MockCLLocationManager.shared.delegate = self.delegate
MockCLLocationManager.shared.startUpdatingLocation()
}
@objc func swizzledStopLocation() {
print("swizzled stop location")
MockCLLocationManager.shared.stopUpdatingLocation()
}
@objc func swizzedRequestLocation() {
print("swizzled request location")
MockCLLocationManager.shared.requestLocation()
}
}
@yobotech
Copy link

May I have the demo link? so I can easily test it.

@wang19891103
Copy link

Your code don't works now.
Only it works 1 second.
Then go back to original CLLocationmanager.

How can I fix it?
Regards!

@sethhoward
Copy link

sethhoward commented Jun 5, 2018

@MS0401 It's either because you're using more than one CLLocationManager in your application and he's set it up with a shared instance that only allows one delegate on CLLocationManager. If the ONLY thing you have is a map, it works "great".

Or the other issue might be the fact that the Timer is poorly implemented. Consider ignoring it and in startUpdatingLocation() invalidate the timer first thing.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment