Mary Doe
Mary Doe

Reputation: 1323

Environment Configuration for DEV and TEST for Swift Project

I am writing tests for an app and have to invoke URL in a webservice. For testing, I want the URL to switch to the test URL instead of the dev URL. From my test target, I sent an environment variable and based on that I return the correct URL. But as you can see it results in a lot of code and I have a lot of other urls.

How can I make it seamless and easy to configure. When on Test environment, I want to return different urls as compared to dev environment.

struct URLConfigurations {
    
    static var loginURL: URL {
        
        // get the environment
        let environment = ProcessInfo.processInfo.environment["ENV"]
        
        if let environment {
            if environment == "TEST" {
                return URL(string: "someURL.com/api/test/login")!
            } else {
                return URL(string: "someURL.com/api/dev/login")!
            }
        } else {
            return URL(string: "someURL.com/api/dev/login")!
        }
    }
}

Upvotes: 0

Views: 502

Answers (1)

Simon McLoughlin
Simon McLoughlin

Reputation: 8475

If you test URLs have the same path as the others, only the domain is different, you could create a networking service that accepts a baseURL in its constructor and then a generic function that just accepts the rest of the path. Then you could pass the baseURL as an ENV variable, and not have to enter it anywhere at all

Rough example from one of my apps, removing the custom stuff:

class NetworkService {
    public let baseURL: URL

    public init(withBaseURL baseURL: URL) {
        self.baseURL = baseURL
    }
    
    public func request<T: Decodable>(path: String, isPOST: Bool, withBody body: Data?, forReturnType: T.Type, completion: @escaping ((Result<T, Error>) -> Void)) {
        var fullURL = self.baseURL
        fullURL.appendingPathComponent(path)
        
       // Perform request, decode and call completion
    }
}

Upvotes: 1

Related Questions