skip to Main Content

I have the following amplitude code that initializes amplitude

import AmplitudeSwift
 
let amplitude = Amplitude(
    configuration: Configuration(
        apiKey: "YOUR-API-KEY"
    )
)
 

The problem is I have to call this code in every file to use amplitude. Is there a way to call it in one file so that I can do amplitude.sharedInstance.track() in other files?

2

Answers


  1. Your question is a bit vague. Do you have the ability to modify the Amplitude class? If so, you could add plumbing to the class that creates a single instance.

    Failing that, you could create a wrapper class that has the plumbing you need. Something like this:

    import AmplitudeSwift
    
    class AmplitudeFactory {
    
    static var _amplitude: Amplitude?
    
    static func amplitude(configuration: Configuration(
            apiKey: String )
       if let amplitude = self._amplitude {
          return amplitude
       } else {
           return Amplitude(
        configuration: Configuration(
            apiKey: apiKey
        )
    }
    

    (That’s ugly because it won’t handle the case where you change the Configuration object or the apiKey, but it gives the idea.)

    Login or Signup to reply.
  2. I am not familiar with that library, but if it does not automatically have a shared instance you can use, you can declare one in an extension.

    
    extension Amplitude
    {
        static let sharedInstance = Amplitude(
            configuration: Configuration(
                apiKey: "YOUR-API-KEY"
            )
        )
    }
    
    // From anywhere in your module
    Amplitude.sharedInstance.track()
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search