iOS - Using struct Constants the right way(with dynamic values)

So i have built this struct:

struct Constants {
    static let BASE_URL = "http://\(CameraManager.ip)/Nexus.cgi?"
    static let WHOIAM_URL = "\(Constants.Url.BASE_URL)action=SERVERWhoAmI"
    static var SERVERPING_URL = "\(Constants.Url.BASE_URL)session=\(CameraManager.session)&action=SERVERPing"
}

and the usage is as follow:

    func refreshSession(success: @escaping () -> Void, failure: @escaping (String) -> Void) {
        self.manager.request(Constants.Url.WHOIAM_URL, method:.get).authenticate(usingCredential: self.utiles.getDigestCredential()).responseJSON { (responseObject) -> Void in

            if responseObject.result.isSuccess {
                let value = responseObject.result.value
                let json = JSON(value!)
                print(CameraManager.session)
                if self.parser.isError(json: json).0 {
                    failure(self.parser.isError(json: json).1)
                } else {
                    self.failedPingCounter = 0
                    CameraManager.session = self.parser.parseWhoAmICall(json: json)
                    success()
                }
            }
      }

   func keepAlive(session: String, success: @escaping () -> Void, failure: @escaping (String) -> Void) {

    self.manager.request(Constants.Url.SERVERPING_URL, method:.get).authenticate(usingCredential: self.utiles.getDigestCredential()).responseJSON { (responseObject) -> Void in


}

As you can see i am updating CameraManager.session value. After updating it i am using it in keepAlive, yet when i check the request i can see it uses the old one... What is the best way to achieve what i want?

Thanks in advanced!

1 answer

  • answered 2019-04-21 10:18 Tom Pearson

    Static vars are implicitly lazy which is why it's not changing even after you change your CameraManager.session value. Since these values are changing I wouldn't make them static and just make them normal computed variables.