<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sajib Ghosh on Medium]]></title>
        <description><![CDATA[Stories by Sajib Ghosh on Medium]]></description>
        <link>https://medium.com/@imsajib333?source=rss-a3364f9ff04a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*VW6ST93ghS9labHEBrvi_A.png</url>
            <title>Stories by Sajib Ghosh on Medium</title>
            <link>https://medium.com/@imsajib333?source=rss-a3364f9ff04a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 23:11:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@imsajib333/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[The Clean Architecture with MVVM in the iOS SwiftUI Project]]></title>
            <link>https://blog.stackademic.com/the-clean-architecture-with-mvvm-in-the-ios-swiftui-project-05dd8fe9ec7a?source=rss-a3364f9ff04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/05dd8fe9ec7a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Sajib Ghosh]]></dc:creator>
            <pubDate>Tue, 28 May 2024 12:53:41 GMT</pubDate>
            <atom:updated>2024-11-08T18:13:51.349Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*fCzhKDAtXgB_2Ny0YB7v6A.jpeg" /><figcaption>Source <a href="https://in.pinterest.com/pin/806918458270826300/">Pinterest</a></figcaption></figure><p><a href="https://blog.cleancoder.com/uncle-bob/2012/08/13/the-clean-architecture.html">Clean architecture</a> is a software design principle introduced by <a href="https://en.wikipedia.org/wiki/Robert_C._Martin">Robert C. Martin</a> (a.k.a <em>Uncle Bob)</em>. There were a few ideas regarding software architecture like Hexagonal Architecture, Onion Architecture, Screaming Architecture etc. The main concept behind each of these architectures is the separation of concern.</p><p>In this article, we will discuss clean architecture and see how we can apply Clean Architecture and MVVM in the iOS SwiftUI app with the help of a <a href="https://github.com/sajib-ghosh-iOS/Product_Clean_Architecture"><strong>demo project</strong></a>.</p><h3>The Clean Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d6lsG9V_wBNXvJxcErw7wA.png" /></figure><p>As we can see in the above graph, the circles represent different areas of software. The outermost layer is the lowest level of the software and as we move in deeper the level of the software will be higher. The inner layer doesn’t know anything about the outer layer. Generally, the further you go the layer is less prone to change.</p><p>The main rule of clean architecture is not to have dependencies from the inner layer to the outer layer. Dependency should be from the outer layer to the inner layer. The arrows pointing from outside to inside are the <strong>dependency rule</strong>.</p><p>There are various layers in clean architecture, after grouping we can say there are three layers — <strong>Presentation</strong>, <strong>Domain</strong> and <strong>Data</strong> layer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f0mHmnThAJBmGwy-vLZqxQ.png" /></figure><h4>Presentation Layer</h4><p>This layer consists of <strong>View</strong> and <strong>ViewModel</strong>. Views are coordinated by ViewModels which executes one or more use cases. The presentation layer <strong>depends</strong> only on the <strong>domain layer</strong>.</p><h4><strong>Domain Layer</strong></h4><p>This is the innermost layer. This layer consists of <strong>Entities</strong>, <strong>Use cases</strong> and <strong>Repository interfaces</strong>. This layer is <strong>not</strong> <strong>dependent</strong> on any other layer. This makes this layer reusable and easy to test. Also, Business logics are written here.</p><h4>Data Layer</h4><p>This layer contains <strong>repository implementations</strong> and <strong>data sources</strong>. Repositories are responsible for coordinating data from data sources. Data sources can be remote or local (for example - core data). The data layer depends on the domain layer. In this layer, we can add mapping of network JSON data to domain models.</p><h4>Dependency Direction and Data Flow</h4><p><strong>View</strong> (UI) calls method from <strong>ViewModel</strong> (Presenter), ViewModel executes <strong>Use Case</strong> and Use Case calls <strong>Repository</strong> for data, Repository fetches data from network or persistent DB. Data then flows back to UI where we show the data.</p><p>The flow looks like this:</p><p>View -&gt; View Model (<strong>Presenter</strong>) -&gt; Use Case (<strong>Domain</strong>) -&gt; Repository (<strong>Data</strong>)</p><p>This flow <strong>violates</strong> the dependency rule of Clean Architecture. As per the dependency rule Domain layer which is the innermost layer should not depend on the Data layer which is an outer layer.</p><blockquote>This can be resolved by the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle"><strong>dependency inversion</strong></a> principle. It states that <strong><em>high-level modules should not depend on low-level modules, but should depend on abstraction.</em></strong></blockquote><p>Instead of depending upon the repository directly from the use cases (domain layer), the Use Case will depend upon the repository interface/protocol. That repository protocol will be inside the domain layer. This way we can invert the direction flow. Let us understand how the direction is inverted in more detail:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EnlGgSGy0aCVc5CzCU78sw.png" /></figure><p>Dependency inversion happens between the data layer and the domain layer. Since the repository interface is inside the domain layer so the data layer is dependent on the domain layer for the repository interface. If the interface changes in the domain layer, the data layer will change accordingly. Here the dependency direction is inverted.</p><p>Interfaces are determined at a higher level (in the domain) and classes (use cases) in their same level depend on them, therefore they depend on abstractions. Additionally, lower-level class (repository) implementations depend on the interfaces defined at a higher level, therefore <em>details </em>now <em>depend on abstractions</em>. This is exactly the rule of dependency inversion. Remember, the inner the circle the higher the level of the software, so the domain layer is higher level than the data layer.</p><p>So, the flow becomes this:</p><p>Presentation Layer — &gt; Domain Layer &lt;—Data Layer</p><p>Enough theory! Now it’s time to understand each layer and MVVM with the help of our <a href="https://github.com/sajib-ghosh-iOS/Product_Clean_Architecture"><strong>example project</strong></a> and sample code.</p><h3>Example Project — ProductClean</h3><p>This is a simple iOS application which fetches product list from a public API and shows them in a list. By clicking on each item in the list it goes to the product details page. This project is built using Clean architecture with MVVM. SwiftUI has been used for UI.</p><p>Clean architecture is used for the separation of concerns among components and MVVM with clean architecture is used to separate concerns between UI and presenter.</p><p>Let us look at the HLD (High-Level Design) and Folder Structure of the app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U9Gvd9-tmoTU-7Vbw27APQ.png" /></figure><p>From the HLD we can see that in this app we have a single module i.e. Products. We can have multiple modules if required. For example, if we want to add the Login and Payment feature in this app we can add the Login and Payment module.</p><p>We know that we have three layers, let us break down each layer:</p><h4><strong>Presentation Layer</strong></h4><p>Presentation Layer = <strong>ViewModel</strong> (Presenter) + <strong>View</strong> (UI)</p><p>Presentation Layer contains ProductListView and ProductListViewModel.</p><p><strong>ProductListView</strong></p><p>ProductListView doesn’t have any access to business logic (Use cases) and doesn’t contain any code related to data manipulation. It just has access to ViewModel. Thus the View becomes <strong>reusable</strong> and <strong>replaceable</strong>.</p><p>View asks ViewModel to fetch the product data and observes the product array from ViewModel. Once it gets the product array it shows the data in the list.</p><pre>import SwiftUI<br><br>struct ProductListView&lt;ViewModel&gt;: View where ViewModel: ProductListViewModelProtocol {<br>    <br>    @ObservedObject private var viewModel: ViewModel<br>    init(viewModel: ViewModel) {<br>        self.viewModel = viewModel<br>    }<br>    <br>    var body: some View {<br>        NavigationStack {<br>            if viewModel.shouldShowLoader() {<br>                ProgressView()<br>                    .progressViewStyle(.circular)<br>            } else {<br>                ProductListLayout(items: viewModel.products)<br>                    .overlay {<br>                        if viewModel.isError {<br>                            ErrorView(errorTitle: AppConstant.errorTitle, errorDescription: viewModel.error) {<br>                                Task {<br>                                    await fetchProducts()<br>                                }<br>                            }<br>                        }<br>                    }<br>                    .navigationTitle(viewModel.title)<br>            }<br>        }<br>        .task {<br>            await fetchProducts()<br>        }<br>    }<br>    <br>    private func fetchProducts() async {<br>        await viewModel.fetchProducts()<br>    }<br>}</pre><p><strong>Note</strong>: <strong>@ObservedObject</strong> property wrapper is used inside View to store ViewModel which is an observable type.</p><p><strong>ProductListViewModel</strong></p><p>ProductListViewModel doesn’t import any UI framework. Thus it becomes reusable. It conforms to ProductListViewModelProtocol which makes it easier to mock the ViewModel and makes it testable.</p><pre>import Foundation<br><br>protocol ProductListViewModelProtocol: ObservableObject {<br>    var products: [ProductListItemViewModel] {get set}<br>    var isError: Bool {get}<br>    var error: String {get}<br>    var isEmpty: Bool {get}<br>    var title: String {get}<br>    func shouldShowLoader() -&gt; Bool<br>    func fetchProducts() async<br>}<br><br>final class ProductListViewModel: ProductListViewModelProtocol {<br>    <br>    @Published var products: [ProductListItemViewModel] = []<br>    @Published var isError: Bool = false<br>    @Published var error: String = &quot;&quot;<br>    var isEmpty: Bool { return products.isEmpty }<br>    var title: String = AppConstant.productListTitle<br>    private let productListUseCase: ProductListUseCase!<br>    init(useCase: ProductListUseCase) {<br>        self.productListUseCase = useCase<br>    }<br>    <br>    /// This method fetches products and catches error if any<br>    @MainActor func fetchProducts() async {<br>        do {<br>            let productList = try await productListUseCase.fetchProductList()<br>            self.products = self.transformFetchedProducts(products: productList)<br>            self.isError = false<br>        } catch {<br>            self.isError = true<br>            if let networkError = error as? NetworkError {<br>                self.error = networkError.description<br>            } else {<br>                self.error = error.localizedDescription<br>            }<br>        }<br>    }<br>    <br>    /// This method maps Product to ProductListItemViewModel<br>    /// - Parameter products:array of Product<br>    /// - Returns: array of ProductListItemViewModel<br>    private func transformFetchedProducts(products: [ProductDomainListDTO]) -&gt; [ProductListItemViewModel] {<br>        products.map { ProductListItemViewModel(id: $0.productId,<br>                                           title: $0.title,<br>                                           description: $0.description,<br>                                                price: $0.price.getAmountWithCurrency(),<br>                                                category: $0.category.capitalized,<br>                                           image: $0.thumbnail) }<br>    }<br>    <br>    /// This method checks if the loader should be shown or not<br>    /// - Returns: True if there the product array is empty and error is not there<br>    func shouldShowLoader() -&gt; Bool {<br>        return (isEmpty &amp;&amp; !isError)<br>    }<br>}</pre><p>ProductListViewModel conforms to <strong>ObservableObject</strong> protocol for storing product array, error and other information. <strong>@Published</strong> property wrapper is added to those properties inside ProductListViewModel that cause the view to update when they change because those properties are accessed in the View. So, when any of the <strong>@Published </strong>properties (products, isError etc.) changes then the view gets updated.</p><p><strong>@MainActor</strong> attribute is used in the fetchProducts function, it will ensure the task runs on the Main Thread. As we can see, inside the fetchProducts function the <strong>@Published </strong>properties are getting updated. We know that those properties are used in Views and when those properties change View gets updated. We want our View (UI) to update on the Main Thread.</p><h4>MVVM</h4><p>The MVVM (Model-View-ViewModel) is a design pattern where the ViewModel acts as a mediator between View and Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sHH80uwXwv_PrVYFbj3DYg.png" /></figure><p>The ViewModel doesn’t import any UI framework thus it becomes reusable and testable. We can use different View implementations for a single ViewModel — for example, we can use UIKit or SwiftUI View for the same ViewModel.</p><p>As discussed above, we have used the <strong>ObservableObject</strong> protocol for data binding but different data bindings can be used for communication — for example delegate, closure, notification, subscriber/publisher etc.</p><p>In our project, MVVM has been used to separate the concern between UI and presenter.</p><h4>Domain Layer</h4><p>Domain Layer = <strong>Use Case </strong>+ <strong>Entity</strong> + <strong>Repository Interface</strong></p><p>Domain Layer consists of <em>ProductListUseCase</em>, <em>ProductDomainListDTO</em> (Entity) + <em>ProductListRepository</em> protocol.</p><p>There can be multiple <em>Use Cases</em> of a particular Module depending on the requirement and one <em>Use Case</em> can depend on another <em>Use Case</em>.</p><p>This layer is the most important layer because the application business rules are written in <em>Use Cases</em>. We can just look at the <em>Use Cases </em>and understand what the application does. This is called Screaming Architecture.</p><p><strong>ProductListUseCase</strong></p><p><em>ProductListUseCase </em>conforms to the ProductListUseCase protocol which contains the fetchProductList function. It has access to the <em>repository </em>and calls product list data from the <em>repository</em>.</p><pre>import Foundation<br><br>protocol ProductListUseCase {<br>    func fetchProductList() async throws -&gt; [ProductDomainListDTO]<br>}<br><br>final class DefaultProductListUseCase: ProductListUseCase {<br>    <br>    private let repository: ProductListRepository<br>    <br>    init(repository: ProductListRepository) {<br>        self.repository = repository<br>    }<br>    <br>    func fetchProductList() async throws -&gt; [ProductDomainListDTO] {<br>        try await repository.fetchProductList()<br>    }<br>}</pre><p><strong>ProductListRepositoryProtocol</strong></p><p>Domain Layer contains <em>ProductListRepositoryProtocol </em>and <em>ProductListUseCase </em>depends on <em>ProductListRepositoryProtocol </em>instead of <em>repository </em>directly. Thus the dependency direction is inverted. We have already discussed this in detail in <strong>Dependency Direction and Data Flow</strong> Section above.</p><pre>protocol ProductListRepository {<br>    func fetchProductList() async throws -&gt; [ProductDomainListDTO]<br>}</pre><p><strong>Note: </strong><em>ProductListRepositoryProtocol </em>is used for <strong>Dependency Inversion</strong>.</p><p><strong>ProductDomainListDTO</strong></p><p><em>ProductDomainListDTO </em>is a Domain Data Transfer Object (<strong>DTO</strong>) which is responsible for working as an intermediate object and transforming the object into a model which will be used in the Presentation Layer.</p><pre>import Foundation<br><br>struct ProductDomainListDTO {<br>    let productId: Int<br>    let title: String<br>    let description: String<br>    let price: Double<br>    var category: String<br>    let thumbnail: String<br>}</pre><h4>Data Layer</h4><p>Data Layer = <strong>Repository Implementation</strong> + <strong>Service / Data Storage</strong></p><p>Data Layer consists of <em>DefaultProductListRepository (</em>which is the Repository implementation) and <em>ProductListService.</em></p><p><strong>DefaultProductListRepository</strong></p><p><em>DefaultProductListRepository </em>has access to <em>ProductListService </em>and fetchProductList function which fetches product data from the service and returns data to the domain.</p><pre>import Foundation<br><br>final class DefaultProductListRepository: ProductListRepository {<br>    <br>    private let service: ProductListService<br>    <br>    init(service: ProductListService) {<br>        self.service = service<br>    }<br>    <br>    func fetchProductList() async throws -&gt; [ProductDomainListDTO] {<br>        try await service.fetchProductListFromNetwork().products.map { $0.toDomain() }<br>    }<br>}</pre><p><strong>Note: </strong>If the app supports offline then <em>ProductListRepository </em>will be injected with Persistent Data Storage ( for example CoreData ). At first <em>repository</em> checks with persistent data storage for cached data, maps the cached data to the domain model if it is present and then returns the data to the domain. And then asks the service to fetch data from the network. After fetching the data, the <em>repository</em> updates the persistent storage with new data and then returns the data to the domain layer after mapping it to the domain model.</p><p><strong>ProductListService</strong></p><p><em>ProductListService </em>has access to apiDataService which is used inside the fetchProductListFromNetwork function to fetch product data from the Network.</p><pre>import Foundation<br><br>protocol ProductListService {<br>    func fetchProductListFromNetwork() async throws -&gt; ProductPageDataListDTO<br>}<br><br>final class DefaultProductListService: ProductListService {<br>    <br>    private let apiDataService: DataTransferService<br>    <br>    init(apiDataService: DataTransferService) {<br>        self.apiDataService = apiDataService<br>    }<br>    <br>    func fetchProductListFromNetwork() async throws -&gt; ProductPageDataListDTO {<br>        let productListNetworkRequest = DefaultNetworkRequest(path: APIEndpoint.products,method: .get)<br>        return try await apiDataService.request(request: productListNetworkRequest)<br>    }<br>}</pre><h4>Network</h4><p>Here, the actual API call occurs with the help of <em>URLSession. </em>First<em> Network Request </em>is created by providing <em>EndPoint</em> and <em>HTTPMethod. </em>Then the <em>URL Request</em> is created. It fetches the data with <em>URL Request. </em>If any error is thrown it handles the error. It also maps data using Decodable.</p><pre>import Foundation<br><br>protocol DataTransferService {<br>    func request&lt;T: Decodable&gt;(request: NetworkRequest) async throws -&gt; T<br>}<br><br>final class DefaultDataTransferService: DataTransferService {<br>    <br>    private let networkManager: NetworkManager<br>    init(networkManager: NetworkManager) {<br>        self.networkManager = networkManager<br>    }<br>    <br>    /// Method to fetch data from Network Manager and Decode the data using the decode method<br>    /// - Parameter request:  Network request<br>    /// - Returns: Decodable type object<br>    func request&lt;T&gt;(request: NetworkRequest) async throws -&gt; T where T : Decodable {<br>        let data = try await networkManager.fetch(request: request)<br>        return try decode(data: data)<br>    }<br>    <br>    /// Method to decode data using JSONDecoder<br>    /// - Parameter data: Data<br>    /// - Returns: Decodable type object<br>    func decode&lt;T&gt;(data: Data) throws -&gt; T where T : Decodable {<br>        do {<br>            let decodedData = try JSONDecoder().decode(T.self, from: data)<br>            return decodedData<br>        } catch {<br>            throw NetworkError.unableToDecode<br>        }<br>    }<br>}<br><br>import Foundation<br><br>protocol NetworkSessionManager {<br>    func request(with config: NetworkConfigurable, request: NetworkRequest) async throws -&gt; (Data?, URLResponse?)<br>}<br>protocol NetworkManager {<br>    func fetch(request: NetworkRequest) async throws -&gt; Data<br>}<br><br>final class DefaultNetworkManager: NetworkManager {<br>    <br>    private let config: NetworkConfigurable<br>    private let sessionManager: NetworkSessionManager<br>    <br>    init(config: NetworkConfigurable,<br>        sessionManager: NetworkSessionManager = DefaultNetworkSessionManager()) {<br>        self.config = config<br>        self.sessionManager = sessionManager<br>    }<br>    <br>    /// Method to fetch data from Session Manager and validates the data and response<br>    /// - Parameter request: Network Request<br>    /// - Returns: Data<br>    func fetch(request: NetworkRequest) async throws -&gt; Data {<br>        let (data, response) = try await sessionManager.request(with: config, request: request)<br>        guard let response = response as? HTTPURLResponse else { throw NetworkError.noResponse }<br>        if response.statusCode != 200 { throw NetworkError.failed }<br>        guard let data = data else { throw NetworkError.noData }<br>        return data<br>    }<br>}</pre><p><strong>Note: </strong>More code related to the Network can be found inside the Networking Folder of <a href="https://github.com/sajib-ghosh-iOS/Product_Clean_Architecture"><strong>Example Project</strong></a>.</p><h3>Dependency Injection (DI)</h3><p><em>Dependency injection</em> is a programming technique in which an object receives other objects that it requires without creating them by itself.</p><p>In our example project we have created a class called <em>AppDIContainer </em>which contains <em>apiDataTransferService. </em>This <em>apiDataTransferService </em>object is required to create the Product Module.</p><pre>import Foundation<br><br>final class AppDIContainer {<br>    <br>    lazy private var apiDataTransferService: DataTransferService = {<br>        let config = ApiDataNetworkConfig(baseURL: AppConfiguration.baseURL)<br>        let sessionManager = DefaultNetworkSessionManager(session: SharedURLSession.shared)<br>        let networkManager = DefaultNetworkManager(config: config, sessionManager: sessionManager)<br>        return DefaultDataTransferService(networkManager: networkManager)<br>    }()<br><br>    lazy var productListView: ProductListView = {<br>        let productsModule = ProductsModule(apiDataTransferService: apiDataTransferService)<br>        return productsModule.generateProductListView()<br>    }()<br>}</pre><p><strong>Note: </strong>We are passing <em>apiDataTransferService </em>to the Product Module as a dependency injection.</p><h3>Conclusion</h3><p>Clean Architecture helps to build highly scalable, testable, maintainable software. It offers separation of concern by segregating the application into multiple layers ensuring that each layer has a specific role and remains isolated from the other. This increases the chance of reusability and ensures adaptability to changing business needs and competitive markets.</p><p>Thanks for reading. Looking forward to hearing from you!</p><p>Happy Coding :)</p><figure><a href="https://buymeacoffee.com/sajibghosh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05dd8fe9ec7a" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-clean-architecture-with-mvvm-in-the-ios-swiftui-project-05dd8fe9ec7a">The Clean Architecture with MVVM in the iOS SwiftUI Project</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The SOLID Principles with Practical Examples in Swift]]></title>
            <link>https://blog.stackademic.com/the-solid-principles-with-practical-examples-in-ios-swift-12f309a29e7b?source=rss-a3364f9ff04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/12f309a29e7b</guid>
            <category><![CDATA[design-principles]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sajib Ghosh]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 07:45:40 GMT</pubDate>
            <atom:updated>2024-11-08T18:16:20.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3xKrOIxlJT8U2X4fT45-jg.png" /></figure><p>In software engineering, SOLID is an acronym for five design principles that aim to make <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented</a> designs more modular, maintainable, readable, flexible, scalable and reusable.</p><p>The Solid principle was introduced by a famous American software engineer <a href="https://en.wikipedia.org/wiki/Robert_C._Martin">Robert C. Martin</a> (a.k.a <em>Uncle Bob).</em></p><p>The five design principles are a set of rules or best practices that every developer should follow. Following the SOLID acronym they are:</p><ol><li><strong>S</strong>ingle Responsibility Principle</li><li><strong>O</strong>pen-Closed Principle</li><li><strong>L</strong>iskov Substitution Principle</li><li><strong>I</strong>nterface Segregation Principle</li><li><strong>D</strong>ependency Inversion Principle</li></ol><p>Now, Let&#39;s grab a cup of coffee and dive into each principle one by one with real-world examples!</p><h4>Single Responsibility Principle (SRP)</h4><p>It states that “<em>a class or module should have only one reason to change</em>”. In other words, a class should only be responsible for one thing, and not have multiple responsibilities.</p><p>This principle helps to keep your code as clean as possible. Also, it has many advantages:</p><ol><li>If your project is managed by different teams and changes the same class for different reasons leading to bugs, SRP will prevent this as the class should have only a single reason to change.</li></ol><p>2. It makes version control easier - for example, if any logic of a feature needs to be updated it would only change related files. There will be less merge conflicts as the responsibility of each class is different.</p><p>Let&#39;s see with a practical example: consider we have an e-commerce app that sells only books. We have to generate an invoice and save that invoice.</p><p>Let’s create the invoice class:</p><pre>class InvoiceWithoutSRP {<br>    <br>    let book: Book<br>    let quantity: Int<br>    let discountPercentage: Double<br>    var total: Double{<br>        calculateTotal()<br>    }<br>    <br>    init(book: Book, quantity: Int, discountPercentage: Double) {<br>        self.book = book<br>        self.quantity = quantity<br>        self.discountPercentage = discountPercentage<br>    }<br>    <br>    func calculateTotal() -&gt; Double {<br>        let bookPrice = book.price<br>        let totalBookPrice = bookPrice * Double(quantity)<br>        let discountAmount = totalBookPrice * discountPercentage/100<br>        let total = totalBookPrice - discountAmount<br>        return total<br>    }<br>    <br>    func printInvoice(){<br>        print(&quot;\(quantity) x \(book.name) $\(book.price)&quot;)<br>        print(&quot;Discount percentage \(discountPercentage)%&quot;)<br>        print(&quot;Total :$\(total)&quot;)<br>    }<br>    <br>    func saveInvoiceToFile(){<br>        //Create a file and save the invoice<br>    }<br>}</pre><p>If you look into the class it does multiple things:</p><ol><li><strong><em>calculateTotal() </em></strong>- this function calculates the total amount.</li><li><strong><em>printInvoice() </em></strong>- this function prints the invoice.</li><li><strong><em>saveInvoice() -</em></strong> this function saves the invoice in the file.</li></ol><p>Now let&#39;s assume the government levies tax on the books sold from our app, so we need to change the business logic in the <strong><em>calculateTotal() </em></strong>function. Also, If we want to change the invoice printing format we would need to change the <strong><em>printInvoice() </em></strong>function. Both functions are in the same class. This clearly violates <strong>SRP</strong>.</p><p>Also, the <strong><em>saveInvoice() </em></strong>function violates SRP. We should never mix business logic with persistence logic.</p><p>We can create two more classes called <strong>InvoicePrinter</strong> and <strong>InvoicePersistence </strong>to separate printing and saving invoice logic so that we will no longer need to modify the same class. It supports <strong>SRP</strong>.</p><p>Our code should look like this:</p><pre>class Invoice {<br>    let book: Book<br>    let quantity: Int<br>    let discountPercentage: Double<br>    let taxRate: Double<br>    var total: Double{<br>        calculateTotal()<br>    }<br>    <br>    init(book: Book, quantity: Int, discountPercentage: Double, taxRate: Double) {<br>        self.book = book<br>        self.quantity = quantity<br>        self.discountPercentage = discountPercentage<br>        self.taxRate = taxRate<br>    }<br>    <br>    func calculateTotal() -&gt; Double {<br>        let bookPrice = book.price<br>        let totalBookPrice = bookPrice * Double(quantity)<br>        let discountAmount = totalBookPrice * discountPercentage/100<br>        let amountWithDiscount = totalBookPrice - discountAmount<br>        let taxAmount = amountWithDiscount * taxRate/100<br>        let total = amountWithDiscount + taxAmount<br>        return total<br>    }<br>}</pre><pre>class InvoicePrinter {<br>    let invoice: Invoice<br>    init(invoice: Invoice) {<br>        self.invoice = invoice<br>    }<br>    func printInvoice(){<br>        print(&quot;Q.\(invoice.quantity) x \(invoice.book.name) $\(invoice.book.price)&quot;)<br>        print(&quot;Discount percentage :\(invoice.discountPercentage)%&quot;)<br>        print(&quot;Tax rate :\(invoice.taxRate)%&quot;)<br>        print(&quot;Total Amount :$\(invoice.total)&quot;)<br>    }<br>}</pre><pre>class InvoicePersistence {<br>    let invoice: Invoice<br>    init(invoice: Invoice) {<br>        self.invoice = invoice<br>    }<br>    func saveInvoiceToFile(){<br>        //Create a file and save the invoice<br>    }<br>}</pre><h4>Open/Closed Principle (OCP)</h4><p>It states that “<em>software entities (classes, modules, functions, etc.) should be open for </em><strong><em>extension</em></strong><em>, but closed for </em><strong><em>modification</em></strong>”. In other words, we can add additional functionality (<strong>extension</strong>) without touching the existing code(<strong>modification</strong>) of a class.</p><p>This principle helps us to reduce potential bugs as <strong>OCP </strong>does not allow us to modify the existing code which is already tested and production ready. <strong>OCP</strong> can be followed with the help of protocol.</p><p>Let&#39;s see with an example: If you remember the <strong>InvoicePersistence </strong>class in the previous example, we are saving the invoice in the file. Now our boss has come and asked to save the invoice in Core Data so that we can search them easily.</p><p>We can simply add one more function called <strong>saveInvoiceToCoreData</strong> to the <strong>InvoicePersistence </strong>class:</p><pre>class InvoicePersistence {<br>    let invoice: Invoice<br>    init(invoice: Invoice) {<br>        self.invoice = invoice<br>    }<br>    func saveInvoiceToFile(){<br>        //Create a file and save the invoice<br>    }<br>    func saveInvoiceToCoreData(){<br>        //Saves invoice to core data<br>    }<br>}</pre><p>But, there is a design problem in the class. We haven’t designed the classes to be easily extendable in the future. We have modified the existing class <strong>InvoicePersistence </strong>in order to add additional functionality. So, it doesn’t obey the <strong>Open Closed Principle</strong>.</p><p>We can refactor the code to make it extendable and obey the principle.</p><p>Instead of using the concrete class <strong>InvoicePersistence, </strong>we can create a protocol called <strong>InvoicePersistenceProtocol </strong>that has only a <strong>save </strong>method. All persistence classes will conform to InvoicePersistenceProtocol and implement this <strong>save </strong>method.</p><pre>protocol InvoicePersistenceProtocol{<br>    func save(invoice: Invoice)<br>}</pre><pre>class FilePersistence: InvoicePersistenceProtocol{<br>    func save(invoice: Invoice) {<br>        //Create a file and save the invoice<br>    }<br>}</pre><pre>class CoreDataPersistence: InvoicePersistenceProtocol{<br>    func save(invoice: Invoice) {<br>        //Saves invoice to core data<br>    }<br>}</pre><pre>class InvoicePersistenceOCP: InvoicePersistenceProtocol {<br>    let persistence: InvoicePersistenceProtocol<br>    init(persistence: InvoicePersistenceProtocol) {<br>        self.persistence = persistence<br>    }<br>    func save(invoice: Invoice) {<br>        persistence.save(invoice: invoice)<br>    }<br>}<br>//calling<br>let coreDatapersistence = CoreDataPersistence()<br>let persistenceOCP = InvoicePersistenceOCP(persistence: coreDatapersistence)<br>persistenceOCP.save(invoice: invoice)</pre><p>Now our persistence module is easily extendable. Again if our boss comes and asks us to give support to the <strong>Realm</strong> database, we can simply add a class called <strong>RealmDataPersistence</strong> which conforms to <strong>InvoicePersistenceProtocol.</strong></p><h4>Liskov Substitution Principle (LSP)</h4><p>The principle was introduced by <a href="https://en.wikipedia.org/wiki/Barbara_Liskov">Barbara Liskov</a> in 1987. according to this principle “<em>Derived or child classes must be substitutable for their base or parent classes”</em>.</p><p>This means, given that a class <strong>Dog </strong>is a subclass of <strong>Animal, </strong>we should be able to pass an object of class <strong>Dog </strong>to<strong> </strong>any method that expects an object of class <strong>Animal </strong>and it should not give any weird output. Assume in the <strong>Animal</strong> class, there is a function called <strong>eat(), </strong>the <strong>Dog </strong>object should also be able to call the <strong>eat() </strong>function as <strong>Dog</strong> is derived from <strong>Animal </strong>and it overrides all the functions of its parent class.</p><p>Let’s see the usage of this principle with a practical example: suppose we have to make an API call with the help of <strong>NSURLRequest</strong> and upon failure, we have to get the request data of the call.</p><p>We can do this in the following way:</p><pre>let requestKey: String = &quot;NSURLRequestKey&quot;<br><br>// This is an NSError subclass that provides additional functionality<br>class CustomError: NSError {<br>    var request: NSURLRequest? {<br>        return self.userInfo[requestKey] as? NSURLRequest<br>    }<br>}<br><br>class FakeAPICall{<br>    //This is a fake API call, it will always return an error.<br>    //notice here the return type is NSError but we have passed CustomError <br>    //which is a subclass of NSError<br>    func callAPI(request: NSURLRequest) -&gt; NSError {<br>        let userInfo: [String:Any] = [requestKey : request]<br>        return CustomError(domain:&quot;LSP.fakeAPI.com&quot;, code:999, userInfo: userInfo)<br>    }<br>}<br><br>//Calling fake API<br>let fakeAPI = FakeAPICall()<br>//Pass an empty object of NSURLRequest<br>let request = NSURLRequest()<br>let error = fakeAPI.callAPI(request: request)<br>if let customError = error as? CustomError {<br>   print(&quot;Request:\(customError.request)&quot;)<br>}</pre><p>Here you can see <strong>CustomError (</strong>child class<strong>) </strong>is substitutable for <strong>Error (</strong>base class<strong>) </strong>and can be used when an <strong>Error</strong> object is required, so it follows <strong>LSP</strong>.</p><h4>Interface Segregation Principle (ISP)</h4><p>It states that “<em>do not force any client to implement an interface which is irrelevant to them”</em>. This means that classes should have specific interfaces for the functionality they provide.</p><p>This principle is similar to the first principle of SOLID (Single Responsibility Principle), instead of classes it applies to interfaces.</p><p>Instead of one fat interface multiple small interfaces are preferred, each interface serving a specific task.</p><p>Let’s see <strong>ISP</strong> with an example: suppose there is a protocol called <strong>GestureProtocol</strong> that provides tap, double tap and long press functionality. And, there is a button called <strong>SuperButton </strong>that performs all the operations. So, <strong>SuperButton </strong>should conform to <strong>GestureProtocol. </strong>Here is what the code looks like:</p><pre>protocol GestureProtocol{<br>    func didTap()<br>    func didDoubleTap()<br>    func didLongPress()<br>}<br><br>class SuperButton : GestureProtocol{<br>    <br>    func didTap() {<br>        //Perform task after a single tap<br>    }<br>    <br>    func didDoubleTap() {<br>        //Perform task after double tap<br>    }<br>    <br>    func didLongPress() {<br>        //Perform task after long press<br>    }<br>}</pre><p>Now, if there is a button called <strong>DoubleTapButton </strong>which only performs a double-tap operation and since we have a single protocol called <strong>GestureProtocol </strong>we end up writing the following code:</p><pre>class DoubleTapButton : GestureProtocol{<br>    <br>    func didTap() {<br>        //Perform task after a single tap<br>    }<br>    <br>    func didDoubleTap() {<br>        //Perform task after double tap<br>    }<br>    <br>    func didLongPress() {<br>        //Perform task after long press<br>    }<br>}</pre><p><strong>DoubleTapButton</strong> un-necessary implement <strong>didTap()</strong> and <strong>didLongPress()</strong> functions. Here it breaks the <strong>ISP</strong>. We can solve the problem using separate protocols instead of a fat one. The refactored code looks like this:</p><pre>protocol SingleTapProtocol{<br>    func didTap()<br>}<br>protocol DoubleTapProtocol{<br>    func didDoubleTap()<br>}<br>protocol LongPressProtocol{<br>    func didLongPress()<br>}<br><br>class SuperButton : SingleTapProtocol, DoubleTapProtocol, LongPressProtocol {<br>    <br>    func didTap() {<br>        //Perform task after a single tap<br>    }<br>    <br>    func didDoubleTap() {<br>        //Perform task after double tap<br>    }<br>    <br>    func didLongPress() {<br>        //Perform task after long press<br>    }<br>}<br><br>class DoubleTapButton : DoubleTapProtocol {<br>    <br>    func didDoubleTap() {<br>        //Perform task after double tap<br>    }<br>    <br>}</pre><p>Now, <strong>DoubleTapButton </strong>only conforms to a specific protocol i.e. <strong>DoubleTapProtocol </strong>and it follows <strong>ISP.</strong></p><h4>Dependency Inversion Principle (DIP)</h4><p>This principle states that “<em>high-level modules should not depend on low-level modules, but should depend on abstraction</em>”. This means the details of the implementation should depend on abstraction but not the other way around.</p><p>The above line states that if a high-level module imports any low-level module then the code becomes tight coupling, changes in one class break another class.</p><p>Let’s consider an example of an iOS app that has a payment feature. The app supports multiple payment methods such as Debit Cards, Stripe, UPI, and Apple Pay.</p><p>We can create four different classes for payment methods and the classes implement a common interface <strong>PaymentMethod</strong>.</p><p>In the <strong>Payment</strong> class if we take four separate payment methods as property then the class will somewhat look like this:</p><pre>class Payment{<br>    var debitCardPayment: DebitCardPayment?<br>    var stripePayment: StripePayment?<br>    var upiPayment: UPIPayment?<br>    var applePayPayment: ApplePayPayment?<br>}</pre><p>This code clearly violates <strong>DIP </strong>as the <strong>Payment</strong> class which is a high-level module is dependent on <strong>DebitCardPayment </strong>which is a low-level module. But as per <strong>DIP, </strong>it should depend on abstraction/protocol. So, instead of taking concrete classes, the <strong>Payment </strong>class takes a property of type <strong>PaymentMethod</strong> protocol. This means the class now depends on abstraction. Now the refactored class looks like this:</p><pre>protocol PaymentMethod{<br>    func pay(amount:Double)<br>}<br><br>class DebitCardPayment: PaymentMethod{<br>    func pay(amount: Double) {<br>        //Process Debit Card Payment<br>    }<br>}<br><br>class StripePayment: PaymentMethod{<br>    func pay(amount: Double) {<br>        //Process Stripe Payment<br>    }<br>}<br><br>class UPIPayment: PaymentMethod{<br>    func pay(amount: Double) {<br>        //Process UPI Payment<br>    }<br>}<br><br>class ApplePayPayment: PaymentMethod{<br>    func pay(amount: Double) {<br>        //Process Apple Pay Payment<br>    }<br>}<br><br>class Payment{<br>    private let paymentMethod : PaymentMethod<br>    init(paymetMethod: PaymentMethod) {<br>        self.paymentMethod = paymetMethod<br>    }<br>    func makePayment(amount: Double) {<br>        paymentMethod.pay(amount: amount)<br>    }<br>}<br>// calling<br>let stripePayment = StripePayment()<br>let payment = Payment(paymetMethod: stripePayment)<br>payment.makePayment(amount: 200.0)</pre><p>The above code follows the Dependency inversion principle. Again if you want to add one more payment method e.g. Credit Card you can do so without changing the Payment method class. Also, you can reuse the Payment class in another project as well as it is now loosely coupled.</p><p>If you look closely <strong>DIP </strong>principle is similar to <strong>Open Closed Principle. </strong>Also<strong>, </strong>keep in mind that Dependency Inversion and <a href="https://en.wikipedia.org/wiki/Dependency_injection">Dependency Injection</a> both are different concepts. People often get confused about it.</p><h4>Conclusion</h4><p>The use of SOLID principles helps produce an efficient architecture. It is also about separating concerns and creating a design that allows sustainable development.</p><p>But these principles, while very useful, are not <em>rules</em>. They’re tools. sometimes we need to make compromises, while maybe violating some of the principles to protect the integrity of the business. Everything is about balancing trade-offs and advantages.</p><p>I hope you enjoyed the Article. You can find all the codes in the <a href="https://github.com/sajib-ghoshInnofied/SolidPrinciplesSwift">GitHub link.</a></p><figure><a href="https://buymeacoffee.com/sajibghosh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12f309a29e7b" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/the-solid-principles-with-practical-examples-in-ios-swift-12f309a29e7b">The SOLID Principles with Practical Examples in Swift</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Core Location for iOS Swift: Tracking User Locations]]></title>
            <link>https://blog.stackademic.com/core-location-for-ios-swift-tracking-user-locations-8e87f154c9e0?source=rss-a3364f9ff04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e87f154c9e0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[core-location]]></category>
            <category><![CDATA[swift-5]]></category>
            <category><![CDATA[ios-16]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sajib Ghosh]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 18:32:14 GMT</pubDate>
            <atom:updated>2025-08-03T07:37:31.899Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*O5RKmsYGq1ZldJbZDm84gQ.jpeg" /></figure><p>Core location is a framework which provides services that determines a device’s geographic location, altitude, and orientation. This framework gathers data with the help of all available components of the device e.g. Wi-Fi, GPS, Bluetooth, and cellular hardware. It provides very powerful high level APIs to configure location requests and notify app for any location information updates.</p><p>There are many popular apps which have utilised this framework e.g: Google Map, Uber, Pokemon Go. You might be making a dating app and you want to suggest partners who are nearby to the user. Or, you’re making an app for your restaurant which will notify the users special offer when they are nearby.</p><p>In this blog we will see how to create a travel tracker app and learn some of the lesser known but effective features of this framework. Imagine you are traveling to a new country and its places, this app will automatically track the places and its locations you visit <strong>even if you close the app</strong>, so you can remember them later and share with your friends. However, tracking location all the time can drain the battery but in this blog we will learn how to minimise battery usage despite tracking location all the time.</p><p>Enough intro, now let’s jump to Xcode and create a project and write some code!</p><h4>Asking for User Location</h4><p>In recent times privacy is a matter of concern. Apple stands pretty strong on keeping users informed of which data an app can gather. So the first and foremost step is to ask permission for tracking user’s location.</p><p><strong>Add a display message for location privacy</strong></p><p>To gather location data, you need to setup two special strings in <strong>info.plist</strong> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uUoDIHDBstpZG56Fpel2Mw.png" /><figcaption>Screenshot of info.plist with location privacy key and value</figcaption></figure><p>The app presents these two strings when it asks for permission. You can change the description based on the requirement of your app.</p><p><strong>Asking for location permissions</strong></p><p>Open AppDelegate.Swift and import CoreLocation at the top of the file. This is a framework which is responsible for providing all the location services.</p><pre>import CoreLocation</pre><p>Also, you need to add a property called locationManager<em> </em>in AppDelegate.Swift. locationManager is an object of CLLocationManager class used for retrieving location information and handling all events triggered by location changes.</p><pre>let locationManager = CLLocationManager()</pre><p>After that, you need to add this line before the return statement in application(_:didFinishLaunchingWithOptions:):</p><pre>//locationManager.requestWhenInUseAuthorization()<br>locationManager.requestAlwaysAuthorization()</pre><p><strong>requestWhenInUseAuthorization()</strong></p><p>This method requests the user’s permission to use location services while the app is in use. It runs asynchronously and prompts the user to grant permission to the app to use location services. The user prompt contains the text from the <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nslocationwheninuseusagedescription">NSLocationWhenInUseUsageDescription</a> key in your app Info.plist file, and the presence of that key is required when calling this method.</p><p>When your app starts standard location services in the foreground, they continue to run in the background if your app has enabled background location updates in the Capabilities tab of your Xcode project. The following points describes how to enable background location updates.</p><p><strong>Enable background location updates</strong></p><p>Add background modes into your project by the following steps: Select target -&gt; Signing &amp; Capabilities -&gt; Capabilities -&gt; Background modes</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tnnvXn8lEt4ke4dRDWnt3g.png" /><figcaption>Add background modes</figcaption></figure><p>And then check Location updates in Background Modes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sVWI97GAXErWuzAzPSbPBw.png" /><figcaption>Enable Location updates in background modes</figcaption></figure><p><strong>requestAlwaysAuthorization()</strong></p><p>This method requests the user’s permission to use location services regardless of whether the app is in use ( foreground or background ) or killed.</p><p>You must call this method before your app can receive location information always. To call this method, you must have both <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nslocationalwaysusagedescription">NSLocationAlwaysUsageDescription</a> and <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/nslocationwheninuseusagedescription">NSLocationWhenInUseUsageDescription</a> keys in your app’s Info.plist file.</p><p>In this blog we will use RequestAlwaysAuthorization() method since we need location update always i.e. when the app is in foreground, background and the app is killed as well.</p><p>Till now our code to request location authorisation in AppDelegate.swift looks like this:</p><pre>import UIKit<br>// Step 1: Import CoreLocation dependency<br>import CoreLocation<br>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>    // Step 2: Declare and initialise a CLLocationManager object globally.<br>    let locationManager = CLLocationManager()<br><br>    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        // Step 3: request authorization<br>        //locationManager.requestWhenInUseAuthorization()<br>        //or<br>        locationManager.requestAlwaysAuthorization()<br>        return true<br>    }<br>}</pre><p>Build and run the project. You should get a dialog similar to this one, it will include the strings you set in the Info.plist file earlier in the blog:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/567/1*20Fyzyespjxz4-mifD2q7Q.png" /><figcaption>Location authorisation dialog</figcaption></figure><p>There are three options: Allow Once — this is a temporary permission, it gives location update for the first time only and it expires when the app is no longer in use. Allow While Using App — this doesn’t expire, it provides location updates every time while the app is in use. Don&#39;t Allow — Denied; no further authorisation requests are allowed.</p><p>For this blog we should select Allow While Using App . To get location update even after the app is terminated/killed we have to allow location access to Always from the device by following the below steps:</p><p>Settings -&gt; Privacy -&gt; Location Services -&gt; App Name ( CoreLocationDemo ) -&gt; Always</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/828/1*9cDzqlv34IflRvTF6WukJA.png" /><figcaption>Allow Location Access to Always</figcaption></figure><p>Now it’s time to get updated location from CLLocationManager.</p><h4>Get User Location</h4><p>We can get user location from the callbacks which are returned from CLLocationManager .</p><p><strong>CLLocationManagerDelegate</strong></p><p>We can get location updates by conforming the CLLocationManagerDelegate which is a protocol and implementing its methods.</p><p>In AppDelegate.Swift after requesting authorisation we need to assign CLLocationManagerDelegate to AppDelegate .</p><pre>// Assign the locationManager delegate to self<br>locationManager.delegate = self</pre><p><strong>Implementing CLLocationManagerDelegate</strong></p><p>CLLocationManagerDelegate is important for handling all the callbacks fired from CLLocationManager. The most important callbacks are <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/3563956-locationmanagerdidchangeauthoriz">locationManagerDidChangeAuthorization(_:)</a>, <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager?language=objc">locationManager:didUpdateLocations:</a> and <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423786-locationmanager?language=objc">locationManager:didFailWithError:</a> . We will discuss these callbacks one by one.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/3563956-locationmanagerdidchangeauthoriz">locationManagerDidChangeAuthorization(_:)</a> is used to know the option user selected from authorisation dialog. Based on the option we can take necessary action based on the business logic of the app.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager?language=objc">locationManager:didUpdateLocations:</a> is used handle the location information when a new location is tracked. Here we get locations array of type CLLocation class, it has multiple properties e.g: altitude, horizontalAccuracy, verticalAccuracy, speedAccuracy, speed, timestamp, courseAccuracy, course.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423786-locationmanager?language=objc">locationManager:didFailWithError:</a> this is invoked when there is an error occurred.</p><pre>//MARK: CLLocationManagerDelegate<br>extension AppDelegate: CLLocationManagerDelegate {<br>    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {<br>        switch manager.authorizationStatus {<br>        case .denied: // Setting option: Never<br>            print(&quot;LocationManager didChangeAuthorization denied&quot;)<br>        case .notDetermined: // Setting option: Ask Next Time<br>            print(&quot;LocationManager didChangeAuthorization notDetermined&quot;)<br>        case .authorizedWhenInUse: // Setting option: While Using the App<br>            print(&quot;LocationManager didChangeAuthorization authorizedWhenInUse&quot;)<br>        case .authorizedAlways: // Setting option: Always<br>            print(&quot;LocationManager didChangeAuthorization authorizedAlways&quot;)<br>        case .restricted: // Restricted by parental control<br>            print(&quot;LocationManager didChangeAuthorization restricted&quot;)<br>        default:<br>            print(&quot;LocationManager didChangeAuthorization&quot;)<br>        }<br>    }<br>    //Handle the location information<br>    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>        print(&quot;locations:\(locations)&quot;)<br>        if let location = locations.first{<br>            print(&quot;altitude: \(location.altitude)&quot;)<br>            print(&quot;floor level: \(location.floor?.level)&quot;)<br>            print(&quot;horizontalAccuracy: \(location.horizontalAccuracy)&quot;)<br>            print(&quot;verticalAccuracy: \(location.verticalAccuracy)&quot;)<br>            print(&quot;speedAccuracy: \(location.speedAccuracy)&quot;)<br>            print(&quot;speed: \(location.speed)&quot;)<br>            print(&quot;timestamp: \(location.timestamp)&quot;)<br>            print(&quot;courseAccuracy: \(location.courseAccuracy)&quot;)<br>            print(&quot;course: \(location.course)&quot;)<br>        }<br>    }<br>    //Invoked when an error has occurred<br>    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {<br>        print(&quot;error:\(error)&quot;)<br>    }<br>}</pre><h4>Monitor User Location Update</h4><p>There are various methods provided by locationManager to update user location. e.g: <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation">startUpdatingLocation()</a> , <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620548-requestlocation">requestLocation()</a> , <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati">startMonitoringSignificantLocationChanges()</a> , <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620558-startupdatingheading">startUpdatingHeading()</a> , Region Monitoring , <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1618692-startmonitoringvisits">startMonitoringVisits()</a>. We will discuss about these methods one by one.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation"><strong>startUpdatingLocation()</strong></a> call this method if you want to get location update frequently. It causes the location manager to obtain a location and notify by calling its <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager">locationManager(_:didUpdateLocations:)</a> method. If you want to generate location update after the device moves certain distance, you can use <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423500-distancefilter">distanceFilter: CLLocationDistance</a> — the minimum distance in meters the device must move horizontally before an update event is generated.</p><p>If you want to receive location while the app is running in background you have to set this Boolean <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620568-allowsbackgroundlocationupdates">allowsBackgroundLocationUpdates: Bool</a> to true. And you must include the <a href="https://developer.apple.com/documentation/bundleresources/information_property_list/uibackgroundmodes">UIBackgroundModes</a> key (with the location value) in their app’s Info.plist file as we discussed in <strong>Enable background location updates </strong>section<strong>.</strong></p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423695-stopupdatinglocation"><strong>stopUpdatingLocation()</strong></a> stops the generation of location updates that comes from <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423750-startupdatinglocation">startUpdatingLocation()</a> .</p><pre>locationManager.startUpdatingLocation() // start location update<br>locationManager.distanceFilter = 100 // update location after 100 meter<br>locationManager.allowsBackgroundLocationUpdates = true // update location in BG<br>//locationManager.startUpdatingLocation() // stop location update</pre><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620548-requestlocation"><strong>requestLocation()</strong></a> call this method if you want to get user’s location for only one time. It causes the location manager to obtain a location and notify by calling its <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager">locationManager(_:didUpdateLocations:)</a> method.</p><pre>locationManager.requestLocation()</pre><p>Above mentioned location services are standard location services. These have high battery impact. High location precision. Great for navigational or fitness apps.</p><p>We can optimise the battery usage by using a property called <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423836-desiredaccuracy">desiredAccuracy: CLLocationAccuracy</a> — the accuracy of the location data that your app wants to receive. If your app isn’t authorised to access precise location information (isAuthorizedForPreciseLocation is false), changes to this property’s value have no effect; the accuracy is always <a href="https://developer.apple.com/documentation/corelocation/kcllocationaccuracyreduced">kCLLocationAccuracyReduced</a>. You can check if the precise location of your app is on or off from the device by following these steps: Settings -&gt; Privacy -&gt; Location Services -&gt; App Name ( CoreLocationDemo ) -&gt; Precise Location. ( Please check the above screenshot ).</p><p>To reduce your app’s impact on battery life, assign a value to this property that’s appropriate for your usage. For example, if you need the current location only within a kilometer, specify <a href="https://developer.apple.com/documentation/corelocation/kcllocationaccuracykilometer">kCLLocationAccuracyKilometer</a>. More accurate location data also takes more time to become available.</p><p>For iOS, the default value of this property is <a href="https://developer.apple.com/documentation/corelocation/kcllocationaccuracybest">kCLLocationAccuracyBest</a>. For macOS, watchOS, and tvOS, the default value is <a href="https://developer.apple.com/documentation/corelocation/kcllocationaccuracyhundredmeters">kCLLocationAccuracyHundredMeters</a>.</p><p>This property effects only the standard location services, not for monitoring significant location changes.</p><pre>locationManager.desiredAccuracy = kCLLocationAccuracyKilometer</pre><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423531-startmonitoringsignificantlocati"><strong>startMonitoringSignificantLocationChanges()</strong></a> call this method if you want to get user’s location when there is a significant change in user’s location. Location events are delivered to your delegate’s <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423615-locationmanager">locationManager(_:didUpdateLocations:)</a> method. It does not rely on the value in the <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423500-distancefilter">distanceFilter</a> property to generate events.</p><p>If you start this service and your app is subsequently terminated/killed, the system automatically relaunches the app into the background if a new event arrives. In such a case, the options dictionary passed to the application(_:willFinishLaunchingWithOptions:) and application(_:didFinishLaunchingWithOptions:) methods of your app delegate contains the key <a href="https://developer.apple.com/documentation/uikit/uiapplication/launchoptionskey/1623101-location">location</a> to indicate that your app was launched because of a location event. Upon relaunch, you must still configure a location manager object and call this method to continue receiving location events. When you restart location services, the current event is delivered to your delegate immediately.</p><p>This location service has medium battery impact. Medium location precision. Low stops precision.</p><pre>locationManager.distanceFilter = 100 // distance filter doesn&#39;t work here<br>locationManager.startMonitoringSignificantLocationChanges()<br>//locationManager.stopMonitoringSignificantLocationChanges()</pre><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620558-startupdatingheading"><strong>startUpdatingHeading()</strong></a> starts the generation of updates that report the user’s current heading. Before calling this method, you should always check the <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1423502-headingavailable">headingAvailable()</a> class method to see whether heading information is supported on the current device. If heading information is not supported, calling this method has no effect and does not result in the delivery of events to your delegate. Heading events are delivered to the <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1621555-locationmanager">locationManager(_:didUpdateHeading:)</a> method of your delegate.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1620569-stopupdatingheading"><strong>stopUpdatingHeading()</strong></a> stops the delivery of location events based on heading updates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/252/1*ssCuI9EuS561yH5c-rTlUw.jpeg" /><figcaption>Update heading</figcaption></figure><pre>if CLLocationManager.headingAvailable() {<br>     locationManager.startUpdatingHeading()<br>     //locationManager.stopUpdatingHeading()<br> }<br><br>func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) {<br>      print(&quot;newHeading:\(newHeading)&quot;)<br>      //newHeading:magneticHeading 342.31 <br>      //trueHeading 341.84 <br>      //accuracy 11.86 <br>      // x +15.056 y +42.590 z -21.730 @ 2023-04-23 09:16:53 +0000<br>  }</pre><p><strong>Region Monitoring</strong> app can be notified when iOS detects user has just entered and exited that region which is defined by the <a href="https://developer.apple.com/documentation/corelocation/clcircularregion">CLCircularRegion</a> with latitude, longitude and radius.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*LPFISyjc_ow8-g1G3OQ4qg.png" /><figcaption>Region monitoring</figcaption></figure><pre>let center = CLLocationCoordinate2D(latitude: 22.593845, longitude: 88.385784)<br>let radius = 200.0 <br>let region = CLCircularRegion(center: center, radius: radius, identifier: &quot;id&quot;)<br><br>// Notified when user enter the region; Callback locationManager:didExitRegion:<br>region.notifyOnEntry = true<br><br>// Notified when user leaves the region; Callback locationManager:didEnterRegion:<br>region.notifyOnExit = true<br><br>locationManager.startMonitoring(for: region)<br><br><br>func locationManager(_ manager: CLLocationManager, didExitRegion region: CLRegion) {<br>    print(&quot;LocationManager didExitRegion \(region)&quot;)<br> }<br>    <br> func locationManager(_ manager: CLLocationManager, didEnterRegion region: CLRegion) {<br>    print(&quot;LocationManager didEnterRegion \(region)&quot;)<br>  }</pre><p>The code above is self-explanatory. When user enters and exits the specific <a href="https://developer.apple.com/documentation/corelocation/clcircularregion">CLCircularRegion</a> , <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423560-locationmanager?language=objc">locationManager:didEnterRegion:</a> and <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1423630-locationmanager?language=objc">locationManager:didExitRegion:</a> will be called respectively.</p><p>It has low battery impact. Great location precision. Requires specific regions in order to monitor.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1618692-startmonitoringvisits"><strong>startMonitoringVisits()</strong></a> call this method if you want to get location update if user visits certain places. It starts the delivery of visit-related events. When a new visit event arrives, the location manager object delivers the event to the <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1621529-locationmanager">locationManager(_:didVisit:)</a> method of its delegate.</p><p>If your app is terminated while this service is active, the system relaunches your app when new visit events are ready to be delivered. Upon relaunch, recreate your location manager object and assign a delegate to begin receiving visit events.</p><p><a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1618693-stopmonitoringvisits"><strong>stopMonitoringVisits()</strong></a> stops the delivery of visit-related events.</p><pre>locationManager.startMonitoringVisits()<br> //locationManager.stopMonitoringVisits()<br><br>func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {<br>    print(&quot;visit:\(visit)&quot;)<br> }</pre><p>For this blog we will be using <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1618692-startmonitoringvisits">startMonitoringVisits()</a> method since in this travel tracker demo app we want to track user’s visited location only. Visit monitoring allows you to track destinations — places where the user stops for a while. It wakes the app whenever a new visit is detected and is very <strong>energy efficient</strong> and not tied to any landmark.</p><h4>Display User location</h4><p>If you use <a href="https://developer.apple.com/documentation/corelocation/cllocationmanager/1618692-startmonitoringvisits">startMonitoringVisits()</a> method and if you have a real device you can test your work right now. Go some places and stop to have a coffee. To get visits data you have to remain at a place for some period of time. You should get callback in <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1621529-locationmanager">locationManager(_:didVisit:)</a> .</p><p>The first method is the callback from CLLocationManager when the new visit is recorded and it provides you with a CLVisit.</p><p>CLVisit has four properties:</p><ol><li>arrivalDate: The date when the visit began.</li><li>departureDate: The date when the visit ended.</li><li>coordinate: The center of the region that the device is visiting.</li><li>horizontalAccuracy: An estimate of the radius (in meters) of the region.</li></ol><p>Now we have to create human readable location description to display to the user.</p><p>First, we need to create CLLocation from CLVisit data. Let’s write the following code in <a href="https://developer.apple.com/documentation/corelocation/cllocationmanagerdelegate/1621529-locationmanager">locationManager(_:didVisit:)</a> .</p><pre>let clLocation = CLLocation(latitude: visit.coordinate.latitude, longitude: visit.coordinate.longitude)</pre><p>Then, we have to use CLGeocoder . Geocoding is the process of converting coordinates into addresses or place names in the real world. If you want to get an address from a set of coordinates, you use <em>reverse</em> geocoding. Thankfully, Core Location gives us a CLGeocoder class which does this for us!</p><p>In AppDelegate.swift add this property at the top of the class:</p><pre>let geoCoder = CLGeocoder()</pre><p>Now, at the bottom of locationManager(_:didVisit:), add the following code:</p><pre>func locationManager(_ manager: CLLocationManager, didVisit visit: CLVisit) {<br>     print(&quot;visit:\(visit)&quot;)<br>     let clLocation = CLLocation(latitude: visit.coordinate.latitude, longitude: visit.coordinate.longitude)<br>      geoCoder.reverseGeocodeLocation(clLocation) { placemarks, error in<br>      if let place = placemarks?.first {<br>         let description = &quot;\(place)&quot;<br>            print(&quot;Location description:\(description)&quot;)<br>        }<br>      }<br>  }</pre><p>Finally, all our hard work paid off! We got the location description and we can store the description in an array and show those descriptions to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*s9Ue-rXscDdFr0DG6uQU4w.jpeg" /></figure><h4>Where to go from here?</h4><p>There are many powerful ways to use location data to build a rich and engaging application. For example, we can track a user’s journey on a map and break it down into travel steps based on the locations they visited. Additionally, we can access the user’s photo gallery, match photos with the corresponding locations, and display them alongside each visited place. This creates a more personalized and immersive travel experience.</p><p>Please don’t forget to give a shout-out or recommend or bookmark this blog if you like it 😎.</p><figure><a href="https://buymeacoffee.com/sajibghosh"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCQqlZr6doDP-cszzpaSpw.png" /></a></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e87f154c9e0" width="1" height="1" alt=""><hr><p><a href="https://blog.stackademic.com/core-location-for-ios-swift-tracking-user-locations-8e87f154c9e0">Core Location for iOS Swift: Tracking User Locations</a> was originally published in <a href="https://blog.stackademic.com/">Stackademic</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding MVVM for iOS in simple words]]></title>
            <link>https://imsajib333.medium.com/understanding-mvvm-for-ios-in-simple-words-3a2889255b31?source=rss-a3364f9ff04a------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a2889255b31</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Sajib Ghosh]]></dc:creator>
            <pubDate>Thu, 11 Mar 2021 13:26:20 GMT</pubDate>
            <atom:updated>2021-03-26T02:35:10.821Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong></p><p>MVVM ( Model View ViewModel ) is a design pattern / software architecture that has been gaining popularity in recent years. This includes a new concept called <strong>View Model </strong>which connects View and Model. The View knows nothing about the Model and vice versa so they become loosely coupled. They are not dependent on each other and they are separable.</p><p><strong>Components</strong></p><p>There are three following components of MVVM:</p><ol><li><strong>Model (M)</strong></li></ol><p>This includes the raw data coming from API, data stored in local databases etc. A project can have multiple models based upon the requirements. For example: after login we get User data, this acts as a model.</p><p><strong>2. View (V)</strong></p><p>This is basically the UI elements that the users interact with. This includes the storyboard where the developers design the UI and View Controller where the UI actions are performed. For example the list view, text fields these are part of the View.</p><p><strong>3. View Model (VM)</strong></p><p>This is the main component of this architecture. View Model is the intermediator between View and Model. It updates the view from model output and updates the model from view input. All the business logic is written here.</p><p><strong>How MVVM works</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RjqTbdUYNVSFGmPa" /></figure><p><strong>MVVM Workflow</strong></p><p>In MVVM the View Model links between View and Model. The View doesn’t know anything about Model and Model also doesn’t know anything about View. The View Model informs the View if there is any change in the Model and similarly the View Model updates the model if there is any change in View.</p><p><strong>Project Structure</strong></p><p>The project structure of MVVM architecture should be the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/286/0*bN8-3JhUukzUyQ7b" /></figure><p>We should divide the project into some modules for specific tasks, and each module is divided into three components but it includes four folders. Let’s check what’s inside those folders:</p><ol><li><strong>View Controller: </strong>Remember, one of the components of MVVM was <strong>View</strong>, so this is basically the <strong>View</strong> Component. In this folder all the UI related elements are there for a specific module. It notifies the ViewModel if the user takes any user action and it needs to be updated to the model.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/0*enuUOBbFez151dZU" /></figure><p><strong>2. View Model:</strong> This is the main component of MVVM. Here all the business logic is written. And it acts as an intermediary between View and Model. This includes only one file for one module. It binds the data to the view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*F09S_dlYORFiJMTz" /></figure><p><strong>3. Model: </strong>All the data is kept inside this component, here in this I have got Image Details from API response, so I have created a ImageDetails struct and kept inside this folder. Also, for dependency injection the dependency has also been kept inside the Model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/0*nQElHaIy12Cadbbo" /></figure><ol><li><strong>DataManager:</strong> This extra folder is added for handling the data (data from API as well as local data) in the proper way. This folder includes four files:</li><li><strong>APIDatamanager</strong>: This class is responsible for making the API call and creating typealias for the completion handler.</li><li><strong>Datamanager</strong>: This is an extra layer for API call, this class is responsible for validating the API after the response comes. It validates the response and it acknowledges ViewModel if it becomes successful or it has some errors. It gets called from ViewModel.</li><li><strong>LocalDatamanager</strong>: This class is responsible only for handling local data. When there is a requirement to save or retrieve data from a local database we can use this class for the same.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*IeoVN9EoD7C6LunB" /></figure><p><strong>Comparison with MVC</strong></p><p>MVC stands for Model View Controller. In the case of MVC there are two components only. One is a Model and the other one is a View Controller. They are tightly coupled with each other. All the business logic and view actions are written in View Controller, so the View Controller sometimes becomes so large that people sometimes call MVC as Massive View Controller. But in MVVM the tasks are separated among the components and easy to understand.</p><p><strong>Advantages</strong></p><ol><li><strong>Testability</strong></li></ol><p>Since the View Model is separated, it becomes easier to test the business logic writing Unit Test cases.</p><p><strong>2. Less Complexity</strong></p><p>The View Controller becomes less lengthy and less complex.</p><p><strong>3. Expressive</strong></p><p>The View Controller separates the business logic from the UI logic.</p><p><strong>4. Specialised</strong></p><p>Each component is responsible for specific tasks. For example the View Controller no longer depends on any Model type and the View Model only focuses on business logic.</p><p><strong>5. Maintainability</strong></p><p>It becomes easier to add any new feature with minimal modification in View Controller.</p><p><strong>Disadvantages</strong></p><p>As MVVM uses one extra layer so the developer has to write some extra code to separate the components and the business logic. For small and simple applications it is not advisable to use MVVM as there is no need to separate the business logic from the View Controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a2889255b31" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>