Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Singleton framework sharedInstance accessible from iOS and WatchKit Target

I made a Swift framework called SharedLocation with a Swift singleton class "SharedLocationManager" inside of it like so:

public class SharedLocationManager: CLLocationManager, CLLocationManagerDelegate
{
public class var sharedInstance: SharedLocationManager {
    struct Static
    {
        static var onceToken : dispatch_once_t = 0
        static var instance : SharedLocationManager? = nil
    }
    dispatch_once(&Static.onceToken)
    {
            Static.instance = SharedLocationManager()
    }
    return Static.instance!
}

public override init()
{
    //do init stuff

}

A shared instance of this class should be accessable from my iOS app (written in Objective-C) and my WatchKit Extension (written in Swift).

i imported the framework in the iOS ViewController like so:

 @import SharedLocation

and in the Watch InterfaceController like so:

import SharedLocation

I am able to get an instance of the singleton class in both targets BUT these are different instances (init() is called twice). When I access the sharedInstance inside the WatchKit Target everything works fine and I get the same instance every time.

Is it even possible to have a singleton class with multiple targets?

like image 581
iVentis Avatar asked Nov 09 '22 17:11

iVentis


1 Answers

No, it is not possible to have a single instance of a singleton shared between your extension and app. Your WatchKit extension and your iOS app are running in different processes. You can save data to a shared group folder if you want to access that data in your extension and your app. You can also use frameworks like MMWormhole if you want to communicate between your extension and app.

like image 165
Stephen Johnson Avatar answered Nov 14 '22 23:11

Stephen Johnson