Skip to content

Instantly share code, notes, and snippets.

@joemasilotti
Last active May 28, 2023 16:54
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save joemasilotti/ed002068cc1239d5e799fae1e4038386 to your computer and use it in GitHub Desktop.
Save joemasilotti/ed002068cc1239d5e799fae1e4038386 to your computer and use it in GitHub Desktop.
A Rails-like environment helper for iOS apps, from https://masilotti.com/rails-like-endpoint-switcher-for-ios-apps/
import Foundation
enum Environment: String {
case development, staging, production
}
extension Environment {
static var current: Environment {
if isAppStore {
return .production
} else if isTestFlight {
return .staging
}
return .development
}
static var isTestFlight: Bool {
if isSimulator {
return false
} else {
if isAppStoreReceiptSandbox, !hasEmbeddedMobileProvision {
return true
} else {
return false
}
}
}
static var isAppStore: Bool {
if isSimulator {
return false
} else {
if isAppStoreReceiptSandbox || hasEmbeddedMobileProvision {
return false
} else {
return true
}
}
}
var isDevelopment: Bool { self == .development }
var isStaging: Bool { self == .staging }
var isProduction: Bool { self == .production }
private static var hasEmbeddedMobileProvision: Bool {
guard Bundle.main.path(forResource: "embedded", ofType: "mobileprovision") == nil else {
return true
}
return false
}
private static var isAppStoreReceiptSandbox: Bool {
if isSimulator {
return false
} else {
guard let url = Bundle.main.appStoreReceiptURL else {
return false
}
guard url.lastPathComponent == "sandboxReceipt" else {
return false
}
return true
}
}
private static var isSimulator: Bool {
#if targetEnvironment(simulator)
return true
#else
return false
#endif
}
}
@joemasilotti
Copy link
Author

I cobbled this together from multiple sources to easily determine the "environment" of an iOS app based on where it was installed from. I use it change the root endpoint of Turbo Native apps in one line.

When I build to the simulator from Xcode I hit my local server. And folks who download from the App Store hit the production endpoint.

enum Endpoint {
    static var root: URL {
        switch Environment.current {
        case .development:
            return URL(string: "http://localhost:3000")!
        case .staging:
            return URL(string: "https://dev.masilotti.com")!
        case .production:
            return URL(string: "https://masilotti.com")!
        }
    }
}

let rootURL = Endpoint.root

I wrote more about this on my blog: https://masilotti.com/rails-like-endpoint-switcher-for-ios-apps/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment