Best architectural approaches for building iOS networking applications (REST clients)

后端 未结 13 1156
-上瘾入骨i
-上瘾入骨i 2020-12-22 14:11

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\

13条回答
  •  旧时难觅i
    2020-12-22 15:07

    I think for now medium project use MVVM architecture and Big project use VIPER architecture and try to achieved

    • Protocol oriented programming
    • Software design patterns
    • S.O.L.D principle
    • Generic programming
    • Don't repeat yourself (DRY)

    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

提交回复
热议问题