I\'m an iOS developer with some experience and this question is really interesting to me. I saw a lot of different resources and materials on this topic, but nevertheless I\
I think for now medium project use MVVM architecture and Big project use VIPER architecture and try to achieved
And Architectural approaches for building iOS networking applications (REST clients)
Separation concern for clean and readable code avoid duplication:
import Foundation
enum DataResponseError: Error {
case network
case decoding
var reason: String {
switch self {
case .network:
return "An error occurred while fetching data"
case .decoding:
return "An error occurred while decoding data"
}
}
}
extension HTTPURLResponse {
var hasSuccessStatusCode: Bool {
return 200...299 ~= statusCode
}
}
enum Result {
case success(T)
case failure(U)
}
dependancy inversion
protocol NHDataProvider {
func fetchRemote(_ val: Model.Type, url: URL, completion: @escaping (Result) -> Void)
}
Main responsible:
final class NHClientHTTPNetworking : NHDataProvider {
let session: URLSession
init(session: URLSession = URLSession.shared) {
self.session = session
}
func fetchRemote(_ val: Model.Type, url: URL,
completion: @escaping (Result) -> Void) {
let urlRequest = URLRequest(url: url)
session.dataTask(with: urlRequest, completionHandler: { data, response, error in
guard
let httpResponse = response as? HTTPURLResponse,
httpResponse.hasSuccessStatusCode,
let data = data
else {
completion(Result.failure(DataResponseError.network))
return
}
guard let decodedResponse = try? JSONDecoder().decode(Model.self, from: data) else {
completion(Result.failure(DataResponseError.decoding))
return
}
completion(Result.success(decodedResponse))
}).resume()
}
}
You will find here is the GitHub MVVM architecture with rest API Swift Project