Repository pattern in iOS Swift

Roopesh Tripathi
2 min readJul 11, 2023

--

for making API calls in an MVC architecture

First, let’s create a protocol for our repository:

protocol UserRepository {
func getUsers(completion: @escaping ([User]?, Error?) -> Void)
}

Next, implement the repository as a class:

class UserRepositoryImpl: UserRepository {
func getUsers(completion: @escaping ([User]?, Error?) -> Void) {
// Make API call to fetch users
// You can use URLSession, Alamofire, or any other networking library here
// Assuming the API call returns an array of User objects

// Replace the API_URL with your actual API endpoint URL
guard let url = URL(string: API_URL) else {
completion(nil, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"]))
return
}

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
// Check for errors
if let error = error {
completion(nil, error)
return
}

// Check the response status code, handle errors if needed

// Parse the response data into User objects
if let data = data {
do {
let users = try JSONDecoder().decode([User].self, from: data)
completion(users, nil)
} catch {
completion(nil, error)
}
} else {
completion(nil, NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey: "No data received"]))
}
}

task.resume()
}
}

Now, in your ViewController, you can use the UserRepository to fetch users:

class ViewController: UIViewController {
private var userRepository: UserRepository!

override func viewDidLoad() {
super.viewDidLoad()

userRepository = UserRepositoryImpl()

// Call the getUsers method to fetch users
userRepository.getUsers { (users, error) in
if let error = error {
// Handle the error
print("Error: \(error.localizedDescription)")
return
}

if let users = users {
// Process the users data
print(users)
}
}
}
}

In this example, the UserRepository protocol defines the contract for fetching users. The UserRepositoryImpl class implements this protocol and handles the API call using URLSession. Finally, in the ViewController, we initialize the UserRepositoryImpl instance and use it to fetch users, handling the response in the completion block.

Please note that this is a simplified example and you need to customize it based on your specific requirements, such as handling authentication, pagination, or error cases.

--

--

Roopesh Tripathi
Roopesh Tripathi

Written by Roopesh Tripathi

👋 Hello, I'm Roopesh Tripathi! 📱 Mobile Developer | iOS Enthusiast | Swift Advocate 💻 Passionate about crafting elegant and efficient mobile apps.

No responses yet