Martin Lockett
Martin Lockett

Reputation: 2589

Using dependancy injection with protocols for iOS framework classes

This is the beginning of my class:

class RoomMonitor: NSObject {

  private var locationManager: CLLocationManager
  private var building: BuildingProtocol
  private var beacons: BeaconsProtocol

  init (thisBuilding:BuildingProtocol, thisLocationManager:CLLocationManager, theseBeacons:BeaconsProtocol) {
    building = thisBuilding
    locationManager = thisLocationManager
    beacons = theseBeacons

I want to use a protocol for the second parameter type instead of CLLocationManager. I've tried declaring a protocol for the bits I need:

protocol LocationManagerProtocol {
  func respondsToSelector(selector:Selector) -> Bool
  func requestAlwaysAuthorization()
  func startMonitoringForRegion(region:CLBeaconRegion)
  func startRangingBeaconsInRegion(region:CLBeaconRegion)
  func startUpdatingLocation()
  var delegate: CLLocationManagerDelegate { set get }
}

and using thisLocationManager:LocationManagerProtocol as the parameter declaration but it says CLLocationManager doesn't conform to the LocationManagerProtocol. I've also tried using extension to add the protocol but it says the methods are public and I'm not allowed to use public in a protocol.

I would appreciate any suggestions on how to achieve what I want.

Upvotes: 0

Views: 232

Answers (1)

Martin Lockett
Martin Lockett

Reputation: 2589

OK, now I understand access control (not sure when it was added to Swift but I'm using Swift 2 beta in Xcode 7 beta 3) all I had to do was insert "public" before "protocol". The default was "internal protocol" and you can't include public items in an internal protocol.

.. and used the extension

extension CLLocationManager:LocationManagerProtocol { }

and I removed the delegate from the protocol as that was a separate problem

Upvotes: 1

Related Questions