Singleton framework sharedInstance accessible from iOS and WatchKit Target
Asked Answered
I

1

6

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?

Intransigeance answered 24/3, 2015 at 11:21 Comment(7)
Both App, and WatchKit run on different instances, so you have two different instances of singleton classes, you can't access one from another.Buoyancy
Is there any workaround??Intransigeance
Why do you want to do this? Want to access location register in the app from watchkit?Buoyancy
It's a running app and I want to start a run on the watch and then be able to continue the run on the phone, so I wanted to do all location based services inside of a public class where both targets can access the same run data and didUpdateLocation methodIntransigeance
Its not possible this way may be a common file in the group folder can help.. See one of my answer here https://mcmap.net/q/1103860/-nsuserdefault-change-notification-handling-in-watchappextensionBuoyancy
and what do you suggest to store inside that common file?Intransigeance
run data, ofcourse? or the data you want to use in the watchkit extension?Buoyancy
A
3

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.

Alloplasm answered 24/3, 2015 at 12:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.