<?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 HITESH KUMAR SINGH on Medium]]></title>
        <description><![CDATA[Stories by HITESH KUMAR SINGH on Medium]]></description>
        <link>https://medium.com/@MaverickHitesh?source=rss-eea821c21c1c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*aFzBTXjdX1oIEENSJyejDA.jpeg</url>
            <title>Stories by HITESH KUMAR SINGH on Medium</title>
            <link>https://medium.com/@MaverickHitesh?source=rss-eea821c21c1c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 19:49:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@MaverickHitesh/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[SOLID Principles in Swift: Overview and Examples]]></title>
            <link>https://medium.com/@MaverickHitesh/solid-principles-in-swift-overview-and-examples-29b678ac0566?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/29b678ac0566</guid>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Wed, 08 Oct 2025 07:40:42 GMT</pubDate>
            <atom:updated>2025-10-08T07:40:42.745Z</atom:updated>
            <content:encoded><![CDATA[<p>The SOLID principles are five essential design guidelines in object-oriented programming that help you write clean, maintainable, and scalable code in Swift. They stand for:</p><ul><li>S: Single Responsibility Principle (SRP)</li><li>O: Open-Closed Principle (OCP)</li><li>L: Liskov Substitution Principle (LSP)</li><li>I: Interface Segregation Principle (ISP)</li><li>D: Dependency Inversion Principle (DIP)</li></ul><p>Let’s explore each with clear Swift examples showing a <em>bad</em> (problematic) and a <em>good</em> (improved) version, discussing why one is bad and why the other is good.</p><h3>1. Single Responsibility Principle (SRP)</h3><p>Principle: A class should have one, and only one, reason to change — meaning one clear responsibility.</p><p>Bad example: A User class that both stores data and handles sending emails.</p><pre>class User {<br>    var name: String<br>    var email: String<br><br>    init(name: String, email: String) {<br>        self.name = name<br>        self.email = email<br>    }<br><br>    func sendEmail(message: String) {<br>        // Code to send email<br>    }<br>}</pre><p><em>Why bad?</em> This class mixes user data management with email sending. If email logic changes, you’d change this class — violating SRP.</p><p>Good example: Separate User data storage and EmailService for sending emails.</p><pre>class User {<br>    var name: String<br>    var email: String<br><br>    init(name: String, email: String) {<br>        self.name = name<br>        self.email = email<br>    }<br>}<br><br>class EmailService {<br>    func sendEmail(to user: User, message: String) {<br>        // Send email logic here<br>    }<br>}</pre><p><em>Why good?</em> Each class has a single responsibility: data vs. communication.</p><h3>2. Open-Closed Principle (OCP)</h3><p>Principle: Classes should be open for extension, but closed for modification.</p><p>Bad example: Adding a new shape forces editing existing ShapeCalculator code.</p><pre>class ShapeCalculator {<br>    func area(of shape: String, dimensions: [Double]) -&gt; Double {<br>        if shape == &quot;rectangle&quot; {<br>            return dimensions[0] * dimensions[1]<br>        } else if shape == &quot;circle&quot; {<br>            return Double.pi * dimensions[0] * dimensions[0]<br>        }<br>        return 0<br>    }<br>}</pre><p><em>Why bad?</em> Every new shape means editing this method, risking bugs.</p><p>Good example: Use protocols for shapes so new shapes can be added without modifying calculator.</p><pre>protocol Shape {<br>    func area() -&gt; Double<br>}<br><br>class Rectangle: Shape {<br>    var width: Double<br>    var height: Double<br><br>    init(width: Double, height: Double) {<br>        self.width = width<br>        self.height = height<br>    }<br><br>    func area() -&gt; Double {<br>        return width * height<br>    }<br>}<br><br>class Circle: Shape {<br>    var radius: Double<br><br>    init(radius: Double) {<br>        self.radius = radius<br>    }<br><br>    func area() -&gt; Double {<br>        return Double.pi * radius * radius<br>    }<br>}<br><br>func printArea(of shape: Shape) {<br>    print(&quot;Area is \(shape.area())&quot;)<br>}</pre><p><em>Why good?</em> To add a new shape, create a new class conforming to Shape. No changes to existing code.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p>Principle: Subclasses should be substitutable for their base classes without altering correctness.</p><p>Bad example: Square inherits from Rectangle but breaks expected behavior.</p><pre>class Rectangle {<br>    var width: Double = 0.0<br>    var height: Double = 0.0<br><br>    func area() -&gt; Double {<br>        return width * height<br>    }<br>}<br><br>class Square: Rectangle {<br>    override var width: Double {<br>        didSet { height = width }<br>    }<br>    override var height: Double {<br>        didSet { width = height }<br>    }<br>}<br><br>let rect: Rectangle = Square()<br>rect.width = 5<br>rect.height = 10<br>print(rect.area()) // Expected 50, but prints 100</pre><p><em>Why bad?</em> A Square modifies width or height to keep them equal, violating the Rectanglecontract and causing unexpected results.</p><p>Good example: Avoid inheritance, use protocols or composition.</p><pre>protocol Shape {<br>    func area() -&gt; Double<br>}<br><br>struct Rectangle: Shape {<br>    var width: Double<br>    var height: Double<br>    func area() -&gt; Double { width * height }<br>}<br><br>struct Square: Shape {<br>    var side: Double<br>    func area() -&gt; Double { side * side }<br>}<br><br>func printArea(of shape: Shape) {<br>    print(shape.area())<br>}</pre><p><em>Why good?</em> Square and Rectangle conform to the same protocol but don&#39;t inherit broken behavior. They behave independently and correctly.</p><h3>4. Interface Segregation Principle (ISP)</h3><p>Principle: Prefer many small, client-specific interfaces over one large, general-purpose interface.</p><p>Bad example: A PaymentMethod protocol that forces all payment classes to implement irrelevant methods.</p><pre>protocol PaymentMethod {<br>    func processCreditCardPayment()<br>    func processPayPalPayment()<br>}<br><br>class CreditCardPayment: PaymentMethod {<br>    func processCreditCardPayment() {<br>        // process credit card<br>    }<br>    func processPayPalPayment() {<br>        // irrelevant here<br>    }<br>}</pre><p><em>Why bad?</em> CreditCardPayment must implement processPayPalPayment even though it doesn&#39;t apply.</p><p>Good example: Split protocols by payment types.</p><pre>protocol CreditCardPayment {<br>    func processCreditCardPayment()<br>}<br>protocol PayPalPayment {<br>    func processPayPalPayment()<br>}<br><br>class CreditCardProcessor: CreditCardPayment {<br>    func processCreditCardPayment() {<br>        // credit card logic<br>    }<br>}</pre><p><em>Why good?</em> Classes only implement what they need, improving clarity and reducing unused code.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p>Principle: High-level modules should not depend on low-level modules. Both should depend on abstractions (protocols).</p><p>Bad example: Car depends directly on concrete GasEngine.</p><pre>class GasEngine {<br>    func start() { print(&quot;Gas engine started&quot;) }<br>}<br><br>class Car {<br>    let engine = GasEngine()<br>    func start() { engine.start() }<br>}</pre><p><em>Why bad?</em> Car is tightly coupled to GasEngine. Changing engine types requires modifying Car.</p><p>Good example: Depend on an Engine protocol injected into Car.</p><pre>protocol Engine {<br>    func start()<br>}<br><br>class GasEngine: Engine {<br>    func start() { print(&quot;Gas engine started&quot;) }<br>}<br><br>class ElectricEngine: Engine {<br>    func start() { print(&quot;Electric engine started&quot;) }<br>}<br><br>class Car {<br>    let engine: Engine<br>    init(engine: Engine) {<br>        self.engine = engine<br>    }<br>    func start() { engine.start() }<br>}<br><br>let gasCar = Car(engine: GasEngine())<br>gasCar.start() // Gas engine started<br><br>let electricCar = Car(engine: ElectricEngine())<br>electricCar.start() // Electric engine started</pre><p><em>Why good?</em> Car depends on abstraction (Engine). It can work with any engine type without modification.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=29b678ac0566" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Smooth Slide-to-Answer Call Pickup UI in SwiftUI]]></title>
            <link>https://medium.com/@MaverickHitesh/creating-a-smooth-slide-to-answer-call-pickup-ui-in-swiftui-efd1ca65970c?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/efd1ca65970c</guid>
            <category><![CDATA[gestures]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[drag-gesture]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 15:05:28 GMT</pubDate>
            <atom:updated>2025-02-28T15:05:28.699Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article, we will build a beautiful and interactive slide-to-answer call UI in SwiftUI. This UI will allow users to answer an incoming call by sliding a button, similar to the iOS call interface. We’ll use SwiftUI’s gestures and animations to create a smooth experience.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*jHnTOqL0jPAaY6ZfIWfjFw.gif" /></figure><h3>Features of Our Call Pickup UI</h3><ul><li><strong>Draggable accept button</strong> that mimics the iOS call answer UI.</li><li><strong>Smooth animations</strong> for a fluid user experience.</li><li><strong>Customisable threshold</strong> for detecting a successful call pickup.</li><li><strong>Dynamic visibility</strong> for the interactive button.</li></ul><p>Let’s dive into the SwiftUI code implementation.</p><h3>SwiftUI Implementation</h3><h3>Step 1: Creating the Call Pickup View</h3><p>We’ll start by creating the CallPickupView struct, which will include a draggable button inside a capsule-shaped background.</p><pre>import SwiftUI<br><br>struct CallPickupView: View {<br>    @State private var offsetX: CGFloat = 0 // Button starts hidden<br>    @State private var isDragging: Bool = false // Controls visibility<br>    private let dragThreshold: CGFloat = 200 // Max distance to answer the call<br>    <br>    var body: some View {<br>        ZStack {<br>            Color.black.edgesIgnoringSafeArea(.all)<br>            <br>            VStack {<br>                Spacer()<br>                Text(&quot;Incoming Call&quot;)<br>                    .font(.largeTitle)<br>                    .foregroundColor(.white)<br>                    .padding(.bottom, 40)<br>                <br>                Spacer()<br>                <br>                // Green Accept Button (Draggable)<br>                ZStack(alignment: .leading) {<br>                    Capsule()<br>                        .fill(Color.green.opacity(0.3))<br>                        .frame(width: 250, height: 70)<br>                        .gesture(<br>                            DragGesture()<br>                                .onChanged { gesture in<br>                                    isDragging = true<br>                                    <br>                                    if gesture.translation.width &gt; 0 {<br>                                        // Left to right<br>                                        offsetX = min(dragThreshold, gesture.translation.width)<br>                                    } else if gesture.translation.width &lt; 0 {<br>                                        // Right to left<br>                                        offsetX = max(0, dragThreshold + gesture.translation.width)<br>                                    }<br>                                }<br>                                .onEnded { _ in<br>                                    if abs(offsetX) &gt;= dragThreshold {<br>                                        print(&quot;Call Answered ✅&quot;)<br>                                        // Perform call action here<br>                                    }<br>                                    withAnimation {<br>                                        offsetX = 0 // Reset position<br>                                        isDragging = false // Hide button again<br>                                    }<br>                                }<br>                        )<br>                    HStack {<br>                        Image(systemName: &quot;phone.fill&quot;)<br>                            .foregroundColor(.white)<br>                            .font(.title)<br>                        <br>                        Text(&quot;Slide to Answer&quot;)<br>                            .foregroundColor(.white)<br>                    }<br>                    .padding(.leading, 50)<br>                    <br>                    // Green Circle (Hidden initially, appears on drag)<br>                    if isDragging || offsetX != 0 {<br>                        CircleView()<br>                            .frame(width: 70, height: 70)<br>                            .offset(x: offsetX)<br>                    }<br>                }<br>                .frame(width: 250, height: 70)<br>                .padding(.bottom, 40)<br>            }<br>        }<br>    }<br>}</pre><h3>Step 2: Creating the Circular Button View</h3><p>To make the draggable button stand out, we’ll define a separate CircleView struct.</p><pre>struct CircleView: View {<br>    var body: some View {<br>        ZStack {<br>            Circle()<br>                .fill(Color.green) // Inner circle color<br>                .frame(width: 70, height: 70)<br><br>            Circle()<br>                .stroke(Color.white, lineWidth: 10) // Outer ring<br>                .frame(width: 70, height: 70)<br>        }<br>    }<br>}</pre><h3>Explanation of the Implementation</h3><ul><li><strong>The background</strong> is set to black to mimic an incoming call screen.</li><li><strong>The main text</strong> displays “Incoming Call” at the top.</li><li><strong>The draggable button</strong> is placed inside a Capsule() shape.</li><li><strong>A </strong><strong>DragGesture</strong> is used to detect user interaction, updating the button&#39;s position dynamically.</li><li><strong>The offset is restricted</strong> to prevent dragging beyond the predefined threshold.</li><li><strong>Animations reset the button</strong> when released if the drag threshold isn’t met.</li><li><strong>The </strong><strong>CircleView</strong> appears only when the user starts dragging.</li></ul><h3>Running the Code</h3><p>To test this UI, simply add CallPickupView() to your SwiftUI preview or your main app.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        CallPickupView()<br>    }<br>}</pre><h3>Customizations and Improvements</h3><ul><li>Adjust the <strong>dragThreshold</strong> to change the required drag distance.</li><li>Modify colors to match your app’s branding.</li><li>Add <strong>haptic feedback</strong> for a more tactile experience.</li><li>Integrate with <strong>CallKit</strong> to manage real phone calls.</li></ul><h3>Conclusion</h3><p>With SwiftUI’s powerful animation and gesture handling capabilities, we created an elegant slide-to-answer UI. This approach provides a seamless user experience and can be enhanced further for real-world applications.</p><p>Happy coding! 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=efd1ca65970c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection — Swift]]></title>
            <link>https://medium.com/@MaverickHitesh/dependency-injection-swift-f2b29aca0096?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/f2b29aca0096</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 08:05:04 GMT</pubDate>
            <atom:updated>2024-06-28T08:05:04.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dependency Injection — Swift</h3><p>Let’s delve deeper into the concepts, benefits, and practical implementation of Dependency Injection (DI) in Swift.</p><h3>What is Dependency Injection?</h3><p>Dependency Injection is a design pattern used to achieve Inversion of Control (IoC) between classes and their dependencies. Instead of a class creating its own dependencies, these dependencies are “injected” into the class from an external source. This promotes loose coupling and enhances testability and maintainability.</p><h3>Why Use Dependency Injection?</h3><ol><li><strong>Loose Coupling</strong>: Classes are less dependent on concrete implementations and more on abstractions (protocols), making it easier to change implementations without modifying the dependent class.</li><li><strong>Testability</strong>: With DI, you can easily replace real dependencies with mock ones, facilitating unit testing.</li><li><strong>Maintainability</strong>: Code becomes more modular and easier to maintain because classes are not tightly bound to their dependencies.</li><li><strong>Flexibility</strong>: It’s easier to swap out dependencies at runtime, which is useful for different configurations or environments.</li></ol><h3>Types of Dependency Injection</h3><ol><li><strong>Constructor Injection</strong>: Dependencies are provided through the initializer of the class.</li><li><strong>Property Injection</strong>: Dependencies are provided through public properties after the object is initialized.</li><li><strong>Method Injection</strong>: Dependencies are provided through methods.</li></ol><h3>Detailed Example Using Constructor Injection</h3><p>Let’s consider a real-world scenario where you have a NetworkService that fetches data from a network and a ViewModelthat uses this service to get data.</p><h4>Step-by-Step Implementation</h4><p>1. Define a Protocol for the Service</p><p>Start by defining a protocol that abstracts the network service. This allows you to swap the real implementation with a mock one during testing.</p><pre>protocol NetworkServiceProtocol {<br>    func fetchData(completion: @escaping (Result&lt;Data, Error&gt;) -&gt; Void)<br>}</pre><p>2. Implement the Real Service</p><p>Create a concrete implementation of the NetworkServiceProtocol.</p><pre>class NetworkService: NetworkServiceProtocol {<br>    func fetchData(completion: @escaping (Result&lt;Data, Error&gt;) -&gt; Void) {<br>        // Imagine this function makes a network call<br>        // For simplicity, let&#39;s just return dummy data<br>        let data = Data()<br>        completion(.success(data))<br>    }<br>}</pre><p>3. Implement the ViewModel</p><p>The ViewModel will depend on the NetworkServiceProtocol.</p><pre>class ViewModel {<br>    private let networkService: NetworkServiceProtocol<br><br>    init(networkService: NetworkServiceProtocol) {<br>        self.networkService = networkService<br>    }<br><br>    func loadData() {<br>        networkService.fetchData { result in<br>            switch result {<br>            case .success(let data):<br>                print(&quot;Data received: \(data)&quot;)<br>            case .failure(let error):<br>                print(&quot;Error: \(error)&quot;)<br>            }<br>        }<br>    }<br>}</pre><p>4. Inject Dependencies</p><p>When you create instances of the ViewModel, inject the dependency via the initializer.</p><pre>let networkService = NetworkService()<br>let viewModel = ViewModel(networkService: networkService)<br>viewModel.loadData()</pre><p>5. Testing</p><p>By using DI, you can easily mock dependencies for testing.</p><pre>class MockNetworkService: NetworkServiceProtocol {<br>    func fetchData(completion: @escaping (Result&lt;Data, Error&gt;) -&gt; Void) {<br>        let dummyData = Data(&quot;Mock data&quot;.utf8)<br>        completion(.success(dummyData))<br>    }<br>}<br><br>let mockService = MockNetworkService()<br>let viewModel = ViewModel(networkService: mockService)<br>viewModel.loadData()</pre><h3>Conclusion</h3><p>Dependency Injection in Swift, whether done manually or with a framework like Swinject, provides a structured way to manage dependencies, promote loose coupling, and enhance testability and maintainability. By injecting dependencies rather than creating them within classes, your code becomes more modular, flexible, and easier to test.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f2b29aca0096" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean architecture and MVVM — Swift]]></title>
            <link>https://medium.com/@MaverickHitesh/clean-architecture-and-mvvm-swift-2667ea253962?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/2667ea253962</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 07:12:24 GMT</pubDate>
            <atom:updated>2024-06-28T07:12:24.238Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean architecture and MVVM — Swift</h3><p>Clean Architecture combined with MVVM in Swift provides a powerful way to structure your iOS applications. This combination promotes separation of concerns, making the code more maintainable, testable, and scalable.</p><h4><strong>Key Concepts</strong></h4><ul><li><strong>Clean Architecture</strong>: Divides the application into layers with clear responsibilities, often including Presentation, Domain, and Data layers.</li><li><strong>MVVM (Model-View-ViewModel)</strong>: Separates the UI logic from the business logic within the Presentation layer.</li></ul><h4>Layers in Clean Architecture</h4><ul><li><strong>Presentation Layer</strong>: Contains the UI (Views) and UI-related logic (ViewModels).</li><li><strong>Domain Layer</strong>: Contains the business logic (Use Cases) and business entities (Models).</li><li><strong>Data Layer</strong>: Handles data operations (Repositories) and data models (Data Sources).</li></ul><h4>Project Structure</h4><pre>MyApp<br>│<br>├── Presentation<br>│   ├── Views<br>│   └── ViewModels<br>│<br>├── Domain<br>│   ├── Entities<br>│   └── UseCases<br>│<br>├── Data<br>│   ├── Repositories<br>│   └── DataSources<br>│<br>├── Common<br>│   └── Utilities &amp; Extensions<br>│<br>└── AppDelegate.swift</pre><h4>Example: Todo App</h4><ol><li><strong>Presentation Layer</strong></li></ol><p><strong>ViewModel: TodoViewModel.swift</strong></p><pre>import SwiftUI<br><br>class TodoViewModel: ObservableObject {<br>    @Published var todos: [Todo] = []<br>    private let getTodosUseCase: GetTodosUseCase<br>    private let addTodoUseCase: AddTodoUseCase<br><br>    init(getTodosUseCase: GetTodosUseCase, addTodoUseCase: AddTodoUseCase) {<br>        self.getTodosUseCase = getTodosUseCase<br>        self.addTodoUseCase = addTodoUseCase<br>        fetchTodos()<br>    }<br><br>    func fetchTodos() {<br>        todos = getTodosUseCase.execute()<br>    }<br><br>    func addTodo(title: String) {<br>        addTodoUseCase.execute(todo: Todo(title: title))<br>        fetchTodos()<br>    }<br>}</pre><p><strong>View: ContentView.swift</strong></p><pre>import SwiftUI<br><br>struct ContentView: View {<br>    @StateObject private var viewModel: TodoViewModel<br><br>    var body: some View {<br>        VStack {<br>            List(viewModel.todos) { todo in<br>                Text(todo.title)<br>            }<br><br>            HStack {<br>                TextField(&quot;New Todo&quot;, text: $newTodoTitle)<br>                Button(&quot;Add&quot;) {<br>                    viewModel.addTodo(title: newTodoTitle)<br>                    newTodoTitle = &quot;&quot;<br>                }<br>            }<br>            .padding()<br>        }<br>        .onAppear {<br>            viewModel.fetchTodos()<br>        }<br>    }<br><br>    @State private var newTodoTitle: String = &quot;&quot;<br>}<br><br>struct ContentView_Previews: PreviewProvider {<br>    static var previews: some View {<br>        let getTodosUseCase = GetTodosUseCase(repository: MockTodoRepository())<br>        let addTodoUseCase = AddTodoUseCase(repository: MockTodoRepository())<br>        let viewModel = TodoViewModel(getTodosUseCase: getTodosUseCase, addTodoUseCase: addTodoUseCase)<br>        ContentView(viewModel: viewModel)<br>    }<br>}</pre><h4>2. Domain Layer</h4><p><strong>Entity: Todo.swift</strong></p><pre>import Foundation<br><br>struct Todo: Identifiable {<br>    let id: UUID<br>    let title: String<br><br>    init(title: String) {<br>        self.id = UUID()<br>        self.title = title<br>    }<br>}</pre><p><strong>Use Cases: GetTodosUseCase.swift &amp; AddTodoUseCase.swift</strong></p><pre>import Foundation<br><br>class GetTodosUseCase {<br>    private let repository: TodoRepository<br><br>    init(repository: TodoRepository) {<br>        self.repository = repository<br>    }<br><br>    func execute() -&gt; [Todo] {<br>        return repository.getTodos()<br>    }<br>}<br><br>class AddTodoUseCase {<br>    private let repository: TodoRepository<br><br>    init(repository: TodoRepository) {<br>        self.repository = repository<br>    }<br><br>    func execute(todo: Todo) {<br>        repository.addTodo(todo)<br>    }<br>}</pre><h4>3. Data Layer</h4><p><strong>Repository Protocol: TodoRepository.swift</strong></p><pre>import Foundation<br><br>protocol TodoRepository {<br>    func getTodos() -&gt; [Todo]<br>    func addTodo(_ todo: Todo)<br>}</pre><p><strong>Repository Implementation: TodoRepositoryImpl.swift</strong></p><pre>import Foundation<br><br>class TodoRepositoryImpl: TodoRepository {<br>    private var todos: [Todo] = []<br><br>    func getTodos() -&gt; [Todo] {<br>        return todos<br>    }<br><br>    func addTodo(_ todo: Todo) {<br>        todos.append(todo)<br>    }<br>}</pre><p><strong>Mock Repository for Testing: MockTodoRepository.swift</strong></p><pre>import Foundation<br><br>class MockTodoRepository: TodoRepository {<br>    private var todos: [Todo] = []<br><br>    func getTodos() -&gt; [Todo] {<br>        return todos<br>    }<br><br>    func addTodo(_ todo: Todo) {<br>        todos.append(todo)<br>    }<br>}</pre><h3>App Initialization</h3><p><strong>App Initialization: MyApp.swift</strong></p><pre>import SwiftUI<br><br>@main<br>struct MyApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            let repository = TodoRepositoryImpl()<br>            let getTodosUseCase = GetTodosUseCase(repository: repository)<br>            let addTodoUseCase = AddTodoUseCase(repository: repository)<br>            let viewModel = TodoViewModel(getTodosUseCase: getTodosUseCase, addTodoUseCase: addTodoUseCase)<br>            ContentView(viewModel: viewModel)<br>        }<br>    }<br>}</pre><h3>Explanation</h3><p><strong>Presentation Layer</strong>:</p><ul><li>TodoViewModel: Acts as a bridge between the view and the domain layer. It fetches data using use cases and exposes it to the view.</li><li>ContentView: A SwiftUI view that displays a list of todos and a text field for adding new todos.</li></ul><p><strong>Domain Layer</strong>:</p><ul><li>Todo: The entity representing a todo item.</li><li>GetTodosUseCase and AddTodoUseCase: Use cases that encapsulate the business logic. They interact with the repository to perform actions.</li></ul><p><strong>Data Layer</strong>:</p><ul><li>TodoRepository: A protocol that defines the methods for accessing todo data.</li><li>TodoRepositoryImpl: A concrete implementation of the TodoRepository that stores todos in memory.</li><li>MockTodoRepository: A mock implementation of the repository for testing purposes.</li></ul><h3>Benefits of Combining Clean Architecture and MVVM</h3><ul><li><strong>Separation of Concerns</strong>: Each layer has a well-defined responsibility, making the codebase easier to understand and maintain.</li><li><strong>Testability</strong>: Use cases and repositories can be easily tested in isolation.</li><li><strong>Scalability</strong>: The architecture scales well with the increasing complexity of the app.</li><li><strong>Reusability</strong>: Use cases and entities can be reused across different parts of the app.</li></ul><p>By following this approach, you can build a robust and maintainable SwiftUI app using MVVM and Clean Architecture principles.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2667ea253962" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test driven development — Analytics Manager using Swift]]></title>
            <link>https://medium.com/@MaverickHitesh/test-driven-development-analytics-manager-using-swift-35bf7d89fa48?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/35bf7d89fa48</guid>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[analytics]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 11:04:56 GMT</pubDate>
            <atom:updated>2024-06-18T11:04:56.616Z</atom:updated>
            <content:encoded><![CDATA[<h3>Test driven development — Analytics Manager using Swift</h3><p>Creating an analytics class in Swift that supports multiple analytical libraries involves designing a flexible interface that can easily switch between different analytics providers. We’ll use a protocol-based approach to define the interface for analytics events and create implementations for different analytics libraries. We’ll also write test cases to ensure our class works as expected.</p><h4>Step-by-Step Guide</h4><ol><li><strong>Define the Analytics Protocol</strong></li></ol><p>Create a protocol that outlines the basic analytics functionality.</p><pre>import Foundation<br><br>protocol AnalyticsService {<br>    func logEvent(name: String, parameters: [String: Any]?)<br>}</pre><p><strong>2. Create Implementations for Different Analytics Libraries</strong></p><p>For demonstration, let’s assume we have two analytics libraries: FirebaseAnalytics and MixpanelAnalytics. We&#39;ll create mock implementations for these libraries.</p><p><strong>FirebaseAnalytics Implementation</strong></p><p>Create a file named FirebaseAnalyticsService.swift.</p><pre>import Foundation<br><br>class FirebaseAnalyticsService: AnalyticsService {<br>    func logEvent(name: String, parameters: [String : Any]?) {<br>        // Replace with actual Firebase Analytics logging code<br>        print(&quot;Logging event to Firebase: \(name), parameters: \(String(describing: parameters))&quot;)<br>    }<br>}</pre><p><strong>MixpanelAnalytics Implementation</strong></p><p>Create a file named MixpanelAnalyticsService.swift.</p><pre>import Foundation<br><br>class MixpanelAnalyticsService: AnalyticsService {<br>    func logEvent(name: String, parameters: [String : Any]?) {<br>        // Replace with actual Mixpanel Analytics logging code<br>        print(&quot;Logging event to Mixpanel: \(name), parameters: \(String(describing: parameters))&quot;)<br>    }<br>}</pre><p><strong>3. Create the Analytics Manager</strong></p><p>The analytics manager will be responsible for using the appropriate analytics service.</p><p>Create a file named AnalyticsManager.swift.</p><pre>import Foundation<br><br>class AnalyticsManager {<br>    static let shared = AnalyticsManager()<br>    <br>    private var services: [AnalyticsService] = []<br>    <br>    private init() {}<br>    <br>    func addService(_ service: AnalyticsService) {<br>        services.append(service)<br>    }<br>    <br>    func logEvent(name: String, parameters: [String: Any]? = nil) {<br>        for service in services {<br>            service.logEvent(name: name, parameters: parameters)<br>        }<br>    }<br>}</pre><p><strong>4. Write Unit Tests</strong></p><p>Create a test file named AnalyticsManagerTests.swift.</p><pre>import XCTest<br><br>@testable import YourProjectName<br><br>class MockAnalyticsService: AnalyticsService {<br>    var loggedEvents: [(name: String, parameters: [String: Any]?)] = []<br>    <br>    func logEvent(name: String, parameters: [String : Any]?) {<br>        loggedEvents.append((name: name, parameters: parameters))<br>    }<br>}<br><br>class AnalyticsManagerTests: XCTestCase {<br>    <br>    var analyticsManager: AnalyticsManager!<br>    var mockService1: MockAnalyticsService!<br>    var mockService2: MockAnalyticsService!<br>    <br>    override func setUp() {<br>        super.setUp()<br>        analyticsManager = AnalyticsManager.shared<br>        mockService1 = MockAnalyticsService()<br>        mockService2 = MockAnalyticsService()<br>        analyticsManager.addService(mockService1)<br>        analyticsManager.addService(mockService2)<br>    }<br>    <br>    override func tearDown() {<br>        mockService1 = nil<br>        mockService2 = nil<br>        analyticsManager = nil<br>        super.tearDown()<br>    }<br>    <br>    func testLogEvent() {<br>        let eventName = &quot;test_event&quot;<br>        let eventParameters: [String: Any] = [&quot;key&quot;: &quot;value&quot;]<br>        <br>        analyticsManager.logEvent(name: eventName, parameters: eventParameters)<br>        <br>        XCTAssertEqual(mockService1.loggedEvents.count, 1)<br>        XCTAssertEqual(mockService1.loggedEvents.first?.name, eventName)<br>        XCTAssertEqual(mockService1.loggedEvents.first?.parameters?[&quot;key&quot;] as? String, &quot;value&quot;)<br>        <br>        XCTAssertEqual(mockService2.loggedEvents.count, 1)<br>        XCTAssertEqual(mockService2.loggedEvents.first?.name, eventName)<br>        XCTAssertEqual(mockService2.loggedEvents.first?.parameters?[&quot;key&quot;] as? String, &quot;value&quot;)<br>    }<br>}</pre><h4>Summary</h4><ol><li><strong>AnalyticsService Protocol</strong>: Defines the basic interface for logging events.</li><li><strong>FirebaseAnalyticsService</strong> and <strong>MixpanelAnalyticsService</strong>: Implementations of the AnalyticsService protocol for different libraries.</li><li><strong>AnalyticsManager</strong>: Manages multiple analytics services and logs events to all of them.</li><li><strong>Unit Tests</strong>: Ensures that the AnalyticsManager correctly logs events to multiple services.</li></ol><p>By following this approach, you can easily add support for new analytics libraries by implementing the AnalyticsService protocol and adding the service to the AnalyticsManager. This makes your analytics solution flexible and scalable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35bf7d89fa48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Operation and OperationQueue]]></title>
            <link>https://medium.com/@MaverickHitesh/operation-and-operationqueue-3a26a3dbaa6d?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a26a3dbaa6d</guid>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[operationqueue]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[opération]]></category>
            <category><![CDATA[threads]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 08:29:46 GMT</pubDate>
            <atom:updated>2024-06-18T08:29:46.523Z</atom:updated>
            <content:encoded><![CDATA[<p>In Swift, Operation and OperationQueue provide a high-level way to manage and execute concurrent tasks. Here&#39;s a detailed guide on how to use them.</p><h4><strong>Overview</strong></h4><ul><li><strong>Operation</strong>: An abstract class representing a single unit of work. It can be used to encapsulate any task, including asynchronous ones.</li><li><strong>OperationQueue</strong>: A queue that manages the execution of Operation objects. It can execute operations concurrently or serially.</li></ul><h4>Creating and Using Operations</h4><ol><li><strong>Subclassing </strong><strong>Operation</strong></li></ol><p>To create a custom operation, you subclass Operation and override the main method to define the task.</p><pre>import Foundation<br><br>class MyOperation: Operation {<br>    override func main() {<br>        if isCancelled {<br>            return<br>        }<br><br>        // Your task here<br>        print(&quot;Task is running&quot;)<br><br>        if isCancelled {<br>            return<br>        }<br><br>        // More task logic if needed<br>    }<br>}</pre><p><strong>2. Using BlockOperation</strong></p><p>For simpler tasks, you can use BlockOperation which allows you to define an operation with a closure.</p><pre>let blockOperation = BlockOperation {<br>    print(&quot;Block operation is running&quot;)<br>}</pre><h4>Using OperationQueue</h4><ol><li><strong>Creating an OperationQueue</strong></li></ol><p>You can create an OperationQueue to manage and execute operations.</p><pre>let operationQueue = OperationQueue()</pre><p><strong>2. Adding Operations to the Queue</strong></p><p>Add your operations to the queue to execute them.</p><pre>let myOperation = MyOperation()<br>operationQueue.addOperation(myOperation)<br><br>let anotherBlockOperation = BlockOperation {<br>    print(&quot;Another block operation&quot;)<br>}<br>operationQueue.addOperation(anotherBlockOperation)</pre><h4>Managing Dependencies</h4><p>Operations can have dependencies, meaning one operation won’t start until its dependencies have finished.</p><pre>let operation1 = BlockOperation {<br>    print(&quot;Operation 1&quot;)<br>}<br><br>let operation2 = BlockOperation {<br>    print(&quot;Operation 2&quot;)<br>}<br><br>operation2.addDependency(operation1)<br><br>operationQueue.addOperations([operation1, operation2], waitUntilFinished: false)</pre><h4>Cancelling Operations</h4><p>You can cancel an operation, and it’s good practice to periodically check the isCancelled property in your operation’s main method.</p><pre>myOperation.cancel()</pre><h4>Example: Downloading Images with Operations</h4><p>Here’s an example of a custom operation to download an image:</p><pre>import UIKit<br><br>class ImageDownloadOperation: Operation {<br>    var imageURL: URL<br>    var downloadedImage: UIImage?<br><br>    init(imageURL: URL) {<br>        self.imageURL = imageURL<br>    }<br><br>    override func main() {<br>        if isCancelled {<br>            return<br>        }<br><br>        guard let imageData = try? Data(contentsOf: imageURL) else {<br>            return<br>        }<br><br>        if isCancelled {<br>            return<br>        }<br><br>        if !imageData.isEmpty {<br>            downloadedImage = UIImage(data: imageData)<br>        }<br>    }<br>}<br><br>// Usage example<br>let imageURL = URL(string: &quot;https://example.com/image.jpg&quot;)!<br>let downloadOperation = ImageDownloadOperation(imageURL: imageURL)<br><br>let operationQueue = OperationQueue()<br>operationQueue.addOperation(downloadOperation)<br><br>// After completion, you can access the downloaded image<br>downloadOperation.completionBlock = {<br>    if let image = downloadOperation.downloadedImage {<br>        // Use the downloaded image<br>        print(&quot;Image downloaded successfully&quot;)<br>    }<br>}</pre><h4>Concurrency Management</h4><p>You can control the maximum number of concurrent operations:</p><pre>operationQueue.maxConcurrentOperationCount = 2</pre><h4>Summary</h4><ul><li><strong>Define Custom Operations</strong>: Subclass Operation and override the main method.</li><li><strong>Use BlockOperation</strong>: For simpler tasks, use BlockOperation.</li><li><strong>Create an OperationQueue</strong>: Manage and execute operations using OperationQueue.</li><li><strong>Add Dependencies</strong>: Set dependencies between operations if needed.</li><li><strong>Handle Cancellation</strong>: Check isCancelled in your operation’s main method.</li><li><strong>Concurrency Control</strong>: Set the maximum number of concurrent operations.</li></ul><p>Using Operation and OperationQueue provides a robust framework for managing complex asynchronous tasks in Swift applications.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a26a3dbaa6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift basics]]></title>
            <link>https://medium.com/@MaverickHitesh/swift-basics-6b5af317088a?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5af317088a</guid>
            <category><![CDATA[learn-swift-basics]]></category>
            <category><![CDATA[learn-swift-programming]]></category>
            <category><![CDATA[swi̇ft]]></category>
            <category><![CDATA[swift-basics]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Tue, 18 Jun 2024 08:13:51 GMT</pubDate>
            <atom:updated>2024-06-18T08:13:51.636Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>1. Basic Syntax</strong></h3><p><strong>Variables and Constants</strong></p><pre>var variableName = &quot;Hello, World!&quot; // Mutable<br>let constantName = 42 // Immutable</pre><p><strong>Data Types</strong></p><pre>let integer: Int = 10<br>let double: Double = 10.5<br>let string: String = &quot;Hello&quot;<br>let boolean: Bool = true</pre><h3>2. Control Flow</h3><p><strong>Conditional Statements</strong></p><pre>let score = 85<br><br>if score &gt;= 90 {<br>    print(&quot;A&quot;)<br>} else if score &gt;= 80 {<br>    print(&quot;B&quot;)<br>} else {<br>    print(&quot;C&quot;)<br>}</pre><p><strong>Switch Statement</strong></p><pre>let letter = &quot;a&quot;<br><br>switch letter {<br>case &quot;a&quot;:<br>    print(&quot;First letter&quot;)<br>case &quot;z&quot;:<br>    print(&quot;Last letter&quot;)<br>default:<br>    print(&quot;Some other letter&quot;)<br>}</pre><h3>3. Loops</h3><p><strong>For-In Loop</strong></p><pre>let numbers = [1, 2, 3, 4, 5]<br><br>for number in numbers {<br>    print(number)<br>}</pre><p><strong>While Loop</strong></p><pre>var counter = 5<br><br>while counter &gt; 0 {<br>    print(counter)<br>    counter -= 1<br>}</pre><h3>4. Functions</h3><p><strong>Function Definition and Calling</strong></p><pre>func greet(name: String) -&gt; String {<br>    return &quot;Hello, \(name)!&quot;<br>}<br><br>let greeting = greet(name: &quot;Hitesh&quot;)<br>print(greeting) // Output: Hello, Hitesh!</pre><p><strong>Function with Multiple Parameters</strong></p><pre>func add(a: Int, b: Int) -&gt; Int {<br>    return a + b<br>}<br><br>let sum = add(a: 3, b: 5)<br>print(sum) // Output: 8</pre><h3>5. Optionals</h3><p><strong>Declaring and Unwrapping Optionals</strong></p><pre>var optionalString: String? = &quot;Hello&quot;<br><br>if let unwrappedString = optionalString {<br>    print(unwrappedString) // Output: Hello<br>} else {<br>    print(&quot;optionalString is nil&quot;)<br>}<br><br>// Using guard statement<br>func printName(name: String?) {<br>    guard let name = name else {<br>        print(&quot;Name is nil&quot;)<br>        return<br>    }<br>    print(&quot;Name is \(name)&quot;)<br>}</pre><h3>6. Collections</h3><p><strong>Arrays</strong></p><pre>var fruits: [String] = [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;]<br><br>fruits.append(&quot;Date&quot;)<br>print(fruits) // Output: [&quot;Apple&quot;, &quot;Banana&quot;, &quot;Cherry&quot;, &quot;Date&quot;]<br><br>for fruit in fruits {<br>    print(fruit)<br>}</pre><p><strong>Dictionaries</strong></p><pre>var capitals: [String: String] = [&quot;France&quot;: &quot;Paris&quot;, &quot;Japan&quot;: &quot;Tokyo&quot;]<br><br>capitals[&quot;India&quot;] = &quot;New Delhi&quot;<br>print(capitals) // Output: [&quot;France&quot;: &quot;Paris&quot;, &quot;Japan&quot;: &quot;Tokyo&quot;, &quot;India&quot;: &quot;New Delhi&quot;]<br><br>for (country, capital) in capitals {<br>    print(&quot;\(country): \(capital)&quot;)<br>}</pre><h3>7. Structs and Classes</h3><p><strong>Structs</strong></p><pre>struct Person {<br>    var name: String<br>    var age: Int<br>}<br><br>let person = Person(name: &quot;Hitesh&quot;, age: 25)<br>print(person.name) // Output: Hitesh</pre><p><strong>Classes</strong></p><pre>class Animal {<br>    var name: String<br><br>    init(name: String) {<br>        self.name = name<br>    }<br><br>    func makeSound() {<br>        print(&quot;Some sound&quot;)<br>    }<br>}<br><br>class Dog: Animal {<br>    override func makeSound() {<br>        print(&quot;Bark&quot;)<br>    }<br>}<br><br>let dog = Dog(name: &quot;Rex&quot;)<br>dog.makeSound() // Output: Bark</pre><h3>8. Protocols and Extensions</h3><p><strong>Protocols</strong></p><pre>protocol Greetable {<br>    func greet() -&gt; String<br>}<br><br>struct Greeter: Greetable {<br>    func greet() -&gt; String {<br>        return &quot;Hello!&quot;<br>    }<br>}<br><br>let greeter = Greeter()<br>print(greeter.greet()) // Output: Hello!</pre><p><strong>Extensions</strong></p><pre>extension String {<br>    func reverse() -&gt; String {<br>        return String(self.reversed())<br>    }<br>}<br><br>let originalString = &quot;Hello&quot;<br>let reversedString = originalString.reverse()<br>print(reversedString) // Output: olleH</pre><h3>9. Error Handling</h3><p><strong>Throwing and Handling Errors</strong></p><pre>enum SampleError: Error {<br>    case invalidInput<br>}<br><br>func check(input: Int) throws {<br>    if input &lt; 0 {<br>        throw SampleError.invalidInput<br>    }<br>}<br><br>do {<br>    try check(input: -1)<br>} catch SampleError.invalidInput {<br>    print(&quot;Invalid input!&quot;)<br>}</pre><h3>10. Closures</h3><p>Simple Closure</p><pre>let sayHello = {<br>    print(&quot;Hello&quot;)<br>}<br><br>sayHello() // Output: Hello</pre><p>Closure with Parameters and Return Type</p><pre>let add: (Int, Int) -&gt; Int = { (a, b) in<br>    return a + b<br>}<br><br>let result = add(2, 3)<br>print(result) // Output: 5</pre><h3>Summary</h3><ul><li><strong>Understand Swift Syntax</strong>: Get comfortable with Swift’s syntax for variables, constants, and data types.</li><li><strong>Control Flow</strong>: Practice using conditional statements and loops.</li><li><strong>Functions</strong>: Learn to define and call functions, including those with multiple parameters.</li><li><strong>Optionals</strong>: Know how to work with optionals, including unwrapping them safely.</li><li><strong>Collections</strong>: Be familiar with arrays and dictionaries, including how to manipulate them.</li><li><strong>Structs and Classes</strong>: Understand the difference and how to use them, including inheritance in classes.</li><li><strong>Protocols and Extensions</strong>: Know how to define and implement protocols, and how to extend existing types.</li><li><strong>Error Handling</strong>: Learn how to throw and handle errors in Swift.</li><li><strong>Closures</strong>: Understand how to create and use closures.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5af317088a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up Travis CI for iOS Project]]></title>
            <link>https://medium.com/@MaverickHitesh/setting-up-travis-ci-for-ios-project-b3cb7963b420?source=rss-eea821c21c1c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b3cb7963b420</guid>
            <category><![CDATA[travis]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[travis-ci]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[continuous-integration]]></category>
            <dc:creator><![CDATA[HITESH KUMAR SINGH]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 05:44:08 GMT</pubDate>
            <atom:updated>2019-04-04T05:44:08.354Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I am going to guide you to setup Travis CI for your iOS project.</p><p><strong>What is </strong><a href="https://docs.travis-ci.com/user/for-beginners/"><strong>Continuous Integration (CI)</strong></a><strong>?<br></strong>Continuous Integration is the practice of merging in small code changes frequently — rather than merging in a large change at the end of a development cycle. The goal is to build healthier software by developing and testing in smaller increments.</p><p><strong>Start a new XCode project</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a9URqzFw6lFaV7_fmNpNqA.png" /><figcaption>I have created a sample project. You can use your existing project.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6vxMYKdvV-zP3ApbSFY_A.png" /><figcaption>Name your project.</figcaption></figure><p><strong>Create a repository on GitHub</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IUzi6YBBn1QQWSYoIFL_cw.png" /><figcaption>I have created a public repository to test Travis CI</figcaption></figure><p>Once your repository is ready push your code to the repository.</p><p><strong>Test the xcodebuild command</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whuBgXQvu8E_TvScXhDKKg.png" /></figure><blockquote><strong>xcodebuild</strong> <strong>clean</strong> <strong>build</strong> test -<strong>project</strong> Travis_CIDemo/Travis_CIDemo.xcodeproj -<strong>scheme</strong> Travis_CIDemo -<strong>sdk</strong> iphonesimulator -<strong>destination</strong> “platform=iOS Simulator,OS=12.1,name=iPhone 6” <strong>ONLY_ACTIVE_ARCH</strong>=NO <strong>CODE_SIGNING_REQUIRED</strong>=NO</blockquote><blockquote>We’ll use this command to create our <strong>yml</strong> file for travis-ci.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Npq5L498nC8TwPZISgCReg.png" /><figcaption>On successful execution of command you’ll see ** TEST SUCCEEDED **</figcaption></figure><p><strong>xcodebuild</strong></p><p>To know more about xcodebuild you can use terminal help for detailed documnetation. On terminal, just write:</p><blockquote><strong>man</strong> xcodebuild</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KuO1eKN5PBfipPAwqmgpWw.png" /><figcaption>man xcodebuild.</figcaption></figure><p><a href="https://travis-ci.org/"><strong>Travis CI</strong></a><strong><br></strong>As a continuous integration platform, Travis CI supports your development process by automatically building and testing code changes, providing immediate feedback on the success of the change. Travis CI can also automate other parts of your development process by managing deployments and notifications.</p><p><strong>Prerequisites<br></strong>1. A <a href="https://github.com/">GitHub</a> account.<br>2. Owner permissions for a project hosted on GitHub.</p><p><strong>Get started with Travis CI<br></strong>1. Go to <a href="https://travis-ci.com/">travis-ci.com</a> and <a href="https://travis-ci.com/signin">signup with GitHub</a>.<br>2. Accept the Authorization of Travis CI. You’ll be redirected to GitHub.<br>3. Click the green Activate button, and select the repositories you want to use with Travis CI.<br>4. Add a <strong>.travis.yml</strong> file to your repository to tell Travis CI what to do. I have added a sample yml file content below for an iOS project (you have to change XCode verion for <strong>osx_image, </strong>project path/simulator/iPhone name for <strong>script</strong>).</p><blockquote><strong>os</strong>: osx<br><strong>osx_image</strong>: xcode10.1<br><strong>language</strong>: swift<br><strong>script</strong>: xcodebuild clean build test -project Travis_CIDemo/Travis_CIDemo.xcodeproj -scheme Travis_CIDemo -sdk iphonesimulator -destination “platform=iOS Simulator,OS=12.1,name=iPhone 6” ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO</blockquote><blockquote><strong>os</strong>: osx. // We need to use Mac OS, as we are developing on Mac.<br><strong>osx_imageB: </strong>xcode10.1 // We are specifically specifying on which version of XCode we need to build our code.<br><strong>language: </strong>swift // Here we are specifying the default language of our project.<br><strong>script </strong>//<strong> </strong>This script will run when travis-ci will build our app.</blockquote><p>5. Add the .travis.yml file to git, commit and push, to trigger a Travis CI build:</p><blockquote>Travis only runs builds on the commits you push after you’ve added a <strong>.travis.yml </strong>file.</blockquote><p>6. Check the build status page to see if your build passes or fails, according to the return status of the build command by visiting the <a href="https://travis-ci.com/auth"><strong>Travis CI</strong></a> and selecting your repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BZVujFSiE08JwHpxljfr5Q.png" /></figure><p><strong>Create a new branch</strong></p><p>Create a new branch from master and create a pull request for master. You’ll see Travis will automatically build your branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GRO861qsquEIHDCFhtp1OQ.png" /><figcaption>Build in progress.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TeuLoJszB0bJjlrxNQmr_A.png" /><figcaption>Build successfully passed.</figcaption></figure><p><strong>References:<br></strong>1. <a href="https://travis-ci.org/">https://travis-ci.org</a><br>2. <a href="https://docs.travis-ci.com/user/tutorial/">https://docs.travis-ci.com/user/tutorial/</a><br>3. <a href="https://youtu.be/XMPOns7VIXI">https://youtu.be/XMPOns7VIXI</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b3cb7963b420" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>