swiftswiftuinetworkmanager

SwiftUI API Integration


I'm new to SwiftUI, and I have a question regarding API URLs. Currently, I'm hardcoding the API URL directly into my code, but I'm wondering if there's a better and safer way to store it.

  1. Should I hardcode the API URL directly in my SwiftUI code?
  2. Is there a best practice for securely storing API URLs so they are easy to access and reuse across my project? I’d appreciate any suggestions or examples of how to manage this properly.

Thank you!


Solution

    1. Store as Environment Variable a. Go to Xcode -> Product -> Scheme -> Edit Scheme. b. Under the Run tab, click Environment Variables. c. Add your environment variable, for example: API_URL = https://your-api- url.com/ d.Access the Variable anywhere in project if let apiUrl = ProcessInfo.processInfo.environment["API_URL"] { print(apiUrl) }

    2. You can also store in info.plist file , then you can use that.

    NOTE -> From my opinion you can use these method to store only base url . And for end point make and singleton class for them . because in app we have base url 2-3(like Development, Staging, or Productio) but we have large number of end-point