This guide explains how to perform API calls in StarterAppKit, leveraging the NetworkManager for asynchronous requests and Combine for reactive data handling. StarterAppKit also integrates Alamofire to simplify HTTP networking.
Overview
StarterAppKit includes a NetworkManager utility for managing API calls. It is designed to provide:
Integration with Alamofire: Simplifies HTTP requests and response handling.
Access Token Management: Automatically retrieves and appends valid tokens to requests.
Error Handling: Handles errors such as unauthorized access and network issues.
Reactive Programming: Uses Combine to handle responses reactively.
Key Components
1. NetworkManager
The NetworkManager handles all API calls and returns a Combine publisher, making it easy to integrate with reactive Swift code.
Example: me() API Call
The me() function is used to fetch the current user's profile data.
Code Breakdown:
Key Features:
Uses Alamofire: Handles HTTP requests and responses efficiently.
Token Management: Automatically appends a valid Bearer token to the request header.
Status Code Validation: Reacts to specific status codes (e.g., 401 for unauthorized).
Error Management: Uses Combine's Future to handle success and error states.
2. ViewModel Integration
API calls from the NetworkManager are injected into your ViewModel using the Factory framework for dependency injection.
Example:
Code Breakdown:
Dependency Injection: The networkManager is injected into the ViewModel using Factory.
Combine Integration: The me() function returns a publisher, making it easy to handle the response using sink.
Error Handling:
receiveCompletion handles errors or indicates when the operation is complete.
Prints error messages or status codes for debugging.
Reactive Updates: The receiveValue closure updates the app state or UI in response to API results.
Practical Example: Fetching User Profile Data
Here’s how you can fetch and process user profile data in your ViewModel:
Best Practices
Use Alamofire for Networking:
Leverage its robust capabilities for request handling, response parsing, and error management.
Dependency Injection:
Use Factory to inject the NetworkManager for clean, modular, and testable code.
Error Handling:
Handle common errors like token expiration (401 Unauthorized) gracefully.
Log errors and provide user-friendly messages.
Combine Pipelines:
Use .sink to process responses and completion states.
Store cancellables in a Set<AnyCancellable> to manage memory efficiently.
Model Decoding:
Decode API responses into Swift models (Codable) for easy integration into your app.