<?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 Amsaraj Mariyappan on Medium]]></title>
        <description><![CDATA[Stories by Amsaraj Mariyappan on Medium]]></description>
        <link>https://medium.com/@raj.amsarajm93?source=rss-907b6a94da27------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*5R3VnDaD0EwOIBQWYBOUMg.jpeg</url>
            <title>Stories by Amsaraj Mariyappan on Medium</title>
            <link>https://medium.com/@raj.amsarajm93?source=rss-907b6a94da27------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 23 May 2026 16:24:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@raj.amsarajm93/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[SwiftDat: Building a Persistent SwiftUI App]]></title>
            <link>https://medium.com/@raj.amsarajm93/swiftdat-building-a-persistent-swiftui-app-888866bf3c6f?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/888866bf3c6f</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Tue, 12 Aug 2025 08:19:30 GMT</pubDate>
            <atom:updated>2025-08-12T08:19:30.683Z</atom:updated>
            <content:encoded><![CDATA[<h3>SwiftData: Building a Persistent SwiftUI App</h3><p>SwiftData was introduced in <strong>iOS 17, </strong>and it’s Apple’s modern native persistence framework built specifically for Swift and SwiftUI.<br>It brings a type-safe, Swift-native API to model, store, and query data without the old and boilerplate of <strong>Core Data</strong> or the manual SQL management of <strong>SQLite</strong>.</p><p>In this tutorial, we will build a <strong>Movie </strong>app demonstrating CRUD (Create, Read, Update, Delete) operations with SwiftData, and also see how it stacks up against Core Data and SQLite.</p><h3>Why SwiftData?</h3><p>Before SwiftData, we typically had three main choices for persistence on Apple platforms:</p><h3>SwiftData vs Core Data vs SQLite</h3><p><strong>API Style</strong></p><p><em>SwiftData</em>: Designed with Swift-first, declarative syntax in mind. Feels natural alongside SwiftUI.</p><p><em>Core Data</em>: Stems from the Objective-C; Swift support is bridged, which can lead to verbose and less type-safe code.</p><p><em>SQLite</em>: Pure SQL commands, powerful but entirely manual.</p><p><strong>Learning Curve</strong></p><p><em>SwiftData</em>: Low, especially if we are already building SwiftUI apps.</p><p><em>Core Data</em>: Medium to high, due to concepts like tables, models, and fetch requests.</p><p><em>SQLite</em>: High, as it requires knowledge of SQL syntax and manual schema handling.</p><p><strong>Integration with SwiftUI</strong></p><p><em>SwiftData</em>: Native-with @Query for fetching and @Model for persistence.</p><p><em>Core Data</em>: Possible but requires large code implementations</p><p><em>SQLite</em>: Entirely manual binding to SwiftUI views.</p><p><strong>Boilerplate</strong></p><p><em>SwiftData</em>: behind the scenes, everything is handled automatically.</p><p><em>Core Data</em>: Significant entity descriptions, managed object contexts, migrations.</p><p><em>SQLite</em>: Very high, we have to handle every table, query, and migration.</p><h3>Project Overview</h3><p>Our Movie app will:</p><blockquote><em>Display a list of movies</em></blockquote><blockquote><em>Add new movies</em></blockquote><blockquote><em>Edit existing movies</em></blockquote><blockquote><em>Delete movies</em></blockquote><h3>Model:</h3><p>SwiftData works around @Model classes, which automatically become persistent entities.</p><pre>import SwiftData</pre><pre>@Model<br>class Movie {<br>    var title: String<br>    var year: Int<br>    <br>    init(title: String, year: Int) {<br>        self.title = title<br>        self.year = year<br>    }<br>}</pre><h3>App Entry Point</h3><p>We set up the model container at the app’s root:<br>This tells SwiftData to persist instances of Movie automatically.</p><pre>@main<br>struct SwiftDataCRUDApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            NavigationStack {<br>                MovieScreen()<br>            }<br>        }<br>        .modelContainer(for: [Movie.self])<br>    }<br>}</pre><h3>Reading Data</h3><p>SwiftData’s @Query property wrapper fetches data reactively</p><pre>struct MovieScreen: View {<br>    @Query(sort: \Movie.title, order: .forward) private var movies: [Movie]<br>    @State private var isAddMoviePresented = false</pre><pre>    var body: some View {<br>        MovieItemView(movies: movies)<br>            .toolbar {<br>                ToolbarItem(placement: .topBarTrailing) {<br>                    Button(&quot;Add Movie&quot;) {<br>                        isAddMoviePresented.toggle()<br>                    }<br>                    .sheet(isPresented: $isAddMoviePresented) {<br>                        NavigationStack {<br>                            AddNewMoviceScreen()<br>                        }<br>                    }<br>                }<br>            }<br>    }<br>}</pre><h3>Creating Data</h3><p>The <strong>Add Movie</strong> screen uses the @Environment(\.modelContext) to insert new movies</p><pre>struct AddNewMoviceScreen: View {<br>    @Environment(\.modelContext) private var modelContext<br>    @Environment(\.dismiss) private var dismiss<br>    <br>    @State var title = &quot;&quot;<br>    @State var year = &quot;&quot;<br>    <br>    var body: some View {<br>        Form {<br>            TextField(&quot;Title&quot;, text: $title)<br>            TextField(&quot;Year&quot;, text: $year)<br>        }<br>        .toolbar {<br>            ToolbarItem(placement: .topBarTrailing) {<br>                Button(&quot;Save&quot;) {<br>                    let movie = Movie(title: title, year: Int(year) ?? 0)<br>                    modelContext.insert(movie)<br>                    try? modelContext.save()<br>                    dismiss()<br>                }<br>                .disabled(title.isEmpty || year.isEmpty)<br>            }<br>        }<br>    }<br>}</pre><h3>Updating Data</h3><p>To edit existing movies, simply mutate the model and call save()</p><pre>struct MovieDetailScreen: View {<br>    @Environment(\.modelContext) private var context<br>    let movie: Movie<br>    <br>    @State private var title = &quot;&quot;<br>    @State private var year: Int?<br>    <br>    var body: some View {<br>        Form {<br>            TextField(&quot;Title&quot;, text: $title)<br>            TextField(&quot;Year&quot;, value: $year, format: .number)<br>            Button(&quot;Update&quot;) {<br>                guard let year = year else { return }<br>                movie.title = title<br>                movie.year = year<br>                try? context.save()<br>            }<br>        }<br>        .onAppear {<br>            title = movie.title<br>            year = movie.year<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>SwiftData integrates seamlessly with SwiftUI, making persistent storage feel natural in declarative apps.<br>With just a few lines of code, we can have a fully persistent, reactive CRUD app ready.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=888866bf3c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Fix Unknown iOS App Crashes]]></title>
            <link>https://medium.com/@raj.amsarajm93/how-to-fix-unknown-ios-app-crashes-74d029a0796e?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d029a0796e</guid>
            <category><![CDATA[app-crash]]></category>
            <category><![CDATA[app-crash-recording]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Tue, 10 Dec 2024 11:33:47 GMT</pubDate>
            <atom:updated>2024-12-10T11:33:47.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2m15oI0CPg2icmAxVzPu4Q.png" /></figure><p>Developers often receive reports from users or clients about random app crashes that cannot be reproduced in either App Store builds or local Xcode builds from our side. Diagnosing such elusive issues can be challenging, but there are several effective methods to identify and resolve them</p><p>In this blog, we’ll explore three approaches to investigating unknown crashes:</p><ol><li><strong>Xcode Organizer</strong></li><li><strong>Firebase Crashlytics</strong></li><li><strong>IPS Files from User Devices</strong></li></ol><p><strong>Xcode Organizer</strong></p><p>The Xcode Organizer is a built-in tool that allows you to review crash logs for apps associated with your Apple Developer account. Here’s how you can use it:</p><ol><li>Open <strong>Xcode</strong> and go to the <strong>Window</strong> menu in the top menu bar.</li><li>Select <strong>Organizer</strong>.</li><li>In the Organizer, you’ll see all the apps tied to your Apple Developer account.</li><li>Select the specific app and version where the crashes were reported.</li><li>Review the crash logs listed. These logs include important details such as the crash type, stack trace, and affected devices.</li></ol><p>The Xcode Organizer provides an excellent first step in analyzing crashes, as it centralizes reports from users who have opted into crash reporting via their devices.</p><p><strong>Firebase Crashlytics</strong></p><p>Firebase Crashlytics is another effective tool for diagnosing crashes, especially when you want real-time crash insights. It requires prior integration into your app, so ensure you’ve set it up during development.</p><p>How to Use Crashlytics to Investigate Crashes:</p><ol><li>Log in to your Firebase Console and navigate to the Crashlytics dashboard for your app.</li><li>Review the list of crashes, including detailed stack traces, device models, OS versions, and user events leading up to the crash.</li><li>Use filters to narrow down crashes by app version, severity, or frequency.</li><li>Look for trends or patterns (e.g., a specific device or iOS version).</li></ol><p>Crashlytics often provides breadcrumbs — logs of user interactions and app lifecycle events before the crash — making it easier to understand what might have gone wrong.</p><p><strong>IPS Files from User Devices</strong></p><p>When a crash occurs, the user’s device generates an <strong>Incident Processor Service (IPS)</strong> file, which contains detailed information about the crash. If a user reports a crash, you can guide them to retrieve the file and share it with you.</p><p><strong>Steps to Retrieve an IPS File:</strong></p><ol><li>Navigate to <strong>Settings</strong> &gt; <strong>Privacy &amp; Security</strong> &gt; <strong>Analytics &amp; Improvements</strong> &gt; <strong>Analytics Data</strong> on the user’s device.</li><li>Find the relevant crash report file (it will have a .ips extension and the app&#39;s name in the file name).</li><li>Share the file to developers.</li></ol><p><strong>How to Analyze the IPS File:</strong></p><ol><li>Open the IPS file in Xcode or any text editor.</li><li>Look for key sections such as the <strong>Exception Type</strong>, <strong>Thread State</strong>, and stack traces to identify the root cause.</li><li>Use the <strong>symbolicatecrash</strong> tool in Xcode to decode symbols for better readability if the file includes memory addresses instead of function names.</li></ol><h3>Conclusion</h3><p>Diagnosing unknown app crashes can be challenging, but with tools like Xcode Organizer, Firebase Crashlytics, and IPS files, you can gain valuable insights to resolve these issues effectively. Each method offers unique advantages:</p><ul><li><strong>Xcode Organizer</strong> is great for centralized crash reporting directly tied to your Apple Developer account.</li><li><strong>Firebase Crashlytics</strong> provides real-time insights with additional contextual data about crashes.</li><li><strong>IPS Files</strong> from user devices allow detailed offline analysis for crashes not captured by other tools.</li></ul><p>By combining these approaches, you can systematically address even the most elusive crashes, improving your app’s stability and user experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d029a0796e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Async/Await in Swift]]></title>
            <link>https://medium.com/@raj.amsarajm93/mastering-async-await-in-swift-3428461c60a5?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3428461c60a5</guid>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Sat, 07 Sep 2024 08:14:19 GMT</pubDate>
            <atom:updated>2024-09-07T08:14:19.955Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*L74Ld7gDxoCyO4hyxuPwjA.png" /></figure><p>Swift’s concurrency model has evolved significantly with the introduction of async/await. This modern approach simplifies writing asynchronous code, making it more readable and maintainable. In this blog post, we&#39;ll dive into the key concepts of Swift&#39;s async/await, exploring how to leverage them effectively in your code.</p><h4>1. async</h4><p>The async keyword marks a function as asynchronous, indicating that it may pause its execution to wait for a result. This is the foundation of Swift&#39;s concurrency model, enabling you to write non-blocking code.</p><pre>func fetchData() async -&gt; Data {<br>    // Simulate network request<br>    return Data()<br>}</pre><h4>2. await</h4><p>The await keyword is used to pause the execution of an async function until the asynchronous task completes. It ensures that the code following it won&#39;t run until the awaited task finishes.</p><pre>let data = await fetchData()</pre><h4>3. async throws</h4><p>When a function can throw an error and is asynchronous, it is marked with async throws. This combination allows you to handle potential errors using try await.</p><pre>func fetchData() async throws -&gt; Data {<br>    guard let data = try? Data(contentsOf: URL(string: &quot;https://example.com&quot;)!) else {<br>        throw URLError(.badURL)<br>    }<br>    return data<br>}</pre><h4>4. try await</h4><p>When calling an async throws function, use try await to handle errors and wait for the result. This ensures that any errors are properly caught while waiting for the asynchronous task to complete.</p><pre>do {<br>    let data = try await fetchData()<br>} catch {<br>    print(&quot;Failed to fetch data: \(error)&quot;)<br>}</pre><h4>5. Task {}</h4><p>The Task {} initializer creates a new concurrent task, allowing you to execute asynchronous code in a structured way. This is useful for running async code outside of an async function.</p><pre>Task {<br>    let data = await fetchData()<br>    print(&quot;Data fetched: \(data)&quot;)<br>}</pre><h4>6. async {}</h4><p>Using async {} within a Task allows for parallel execution of multiple asynchronous tasks. This approach is helpful when you need to perform several async operations concurrently.</p><pre>Task {<br>    async {<br>        let data1 = await fetchData()<br>        print(&quot;Data 1 fetched: \(data1)&quot;)<br>    }<br>    async {<br>        let data2 = await fetchData()<br>        print(&quot;Data 2 fetched: \(data2)&quot;)<br>    }<br>}</pre><h4>7. async let</h4><p>The async let keyword allows you to start an asynchronous operation and await its result later. This is especially useful for running multiple async tasks in parallel, improving performance by not waiting for each task sequentially.</p><pre>async let data1 = fetchData()<br>async let data2 = fetchData()</pre><pre>let results = await (data1, data2)<br>print(&quot;Data fetched: \(results)&quot;)</pre><h4>8. Continuation</h4><p>Continuation is a powerful feature that bridges the gap between old completion handler-based APIs and the new async/await model. It allows you to convert callback-based code into an async function.</p><pre>func fetchData() async -&gt; Data {<br>    await withCheckedContinuation { continuation in<br>        // Simulate network request<br>        DispatchQueue.global().async {<br>            continuation.resume(returning: Data())<br>        }<br>    }<br>}</pre><h4>9. withThrowingTaskGroup</h4><p>The withThrowingTaskGroup function lets you create a group of related tasks that can throw errors. You can await the completion of all tasks in the group or handle each result as it becomes available.</p><pre>func fetchAllData() async throws -&gt; [Data] {<br>    try await withThrowingTaskGroup(of: Data.self) { group in<br>        var results: [Data] = []<br>        <br>        for url in urls {<br>            group.addTask {<br>                try await fetchData(from: url)<br>            }<br>        }<br>        <br>        for try await data in group {<br>            results.append(data)<br>        }<br>        <br>        return results<br>    }<br>}</pre><h4>10. Task.cancel</h4><p>The Task.cancel method allows you to cancel a running task, preventing it from completing its work. This is useful for handling scenarios where an async operation is no longer needed.</p><pre>let task = Task {<br>    let data = await fetchData()<br>    print(&quot;Data fetched: \(data)&quot;)<br>}</pre><pre>// Cancel the task before it completes<br>task.cancel()</pre><h3>Conclusion</h3><p>Swift’s async/await model simplifies the complexity of asynchronous programming, making your code more readable and easier to maintain. By mastering the concepts outlined in this guide, you’ll be well-equipped to handle concurrency in Swift effectively. Whether you’re migrating from completion handlers or starting fresh, async/await is a powerful tool that enhances Swift’s capabilities in handling asynchronous tasks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3428461c60a5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS: Protocols in Swift]]></title>
            <link>https://medium.com/@raj.amsarajm93/ios-protocols-in-swift-ebd1a8634198?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebd1a8634198</guid>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[protocol]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Mon, 15 Jun 2020 08:13:09 GMT</pubDate>
            <atom:updated>2020-06-15T08:19:23.239Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ELEAz-FZ1I_XgsRKlHB54A.jpeg" /></figure><p>Here we are going to learn about Protocols and how to use them in your iOS projects.</p><h4>Protocols:</h4><p>A protocols defines the blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality. The protocols can then be adopted by a class, structure, or enumeration to provide an actual implementation of those requirements.</p><p>In addition to specifying requirements that conforming types must implement, you can extend a protocol to implement some of these requirements or to implement additional functionality that conforming types can take advantage of.</p><h4>Syntax of a Protocols:</h4><pre>protocol SampleProtocol {<br>  // we can add here variable and methods without implementation<br>}</pre><p>we can create protocol similar class, enum and struct. After created protocol we can inherit our required class or enum or struct like below.</p><pre>//class<br>class SampleClass: SampleProtocol {<br>}</pre><pre>//struct <br>struct SampleStruct: SampleProtocol {<br>}</pre><pre>//enum <br>enum SampleEnum: SampleProtocol {<br>}</pre><p>also we can inherit multiple protocols one class are separated by commas.</p><pre>class SampleClass: SampleProtocolOne, SampleProtocolTwo {<br>}</pre><p>so basically, we can have a class, struct or enum to conform to a protocol having variables, methods and initializers. After conforming a protocol, you must implement everything defined in it or else it will give an error.</p><h4>Simple Protocol:</h4><pre>protocol Country {<br>  var name: String { get }<br>  var code: String { get }<br>  func details()<br>}</pre><p>When variables are declared inside a protocol they can either be set as ‘get’ or ‘get set’. ‘get’ lets you set the variable to be-a constant, variable, or a computed or read-only property.</p><p>‘get set’ limits the property, you cannot set it to a constant, and it cannot be a computed property.</p><h4>Mutating protocol:</h4><p>It’s sometimes necessary for a method to modify (or <em>mutate</em>) the instance it belongs to. For instance methods on value types (that is, structures and enumerations) you place the <strong>mutating</strong> keyword before a method’s <strong>func</strong> keyword to indicate that the method is allowed to modify the instance it belongs to and any properties of that instance.</p><pre>protocol Switchable {<br>  mutating func switch()<br>}</pre><p>If you implement the Switchable protocol for a structure or enumeration, that structure or enumeration can conform to the protocol by providing an implementation of the switch() method that is also marked as mutating.</p><pre>enum OnOffSwitch: Switchable {<br>  case off, on<br>  mutating func switch() {<br>    switch self {<br>      case .off:<br>         self = .on<br>      case .on:<br>         self = .off<br>   }<br>  }<br>}</pre><pre>var lightSwitch = OnOffSwitch.off<br>lightSwitch.switch()</pre><h4>Delegation:</h4><p>Delegation is a design pattern that enables a class or structure to hand off (or <em>delegate</em>) some of its responsibilities to an instance of another type. Delegation pattern can also be used as a callback kind of mechanism.</p><pre>protocol SampleProtocol {<br>  func doSomeThing()<br>}</pre><pre>class SampleClassOne {<br>    var delegate: SampleProtocol?<br>    func doSomeThing() {<br>        delegate?.doSomeThing()<br>}}</pre><pre>class SampleClassTwo: SampleProtocol {<br>    func doSomeThing() {<br>         print(&quot;delegate called&quot;)<br>}}</pre><pre>var sampleOne = SampleClassOne()<br>var sampleTwo = SampleClassTwo()<br>sampleOne.delegate = sampleTwo<br>sampleOne.doSomeThing()</pre><h4>Protocol Extensions</h4><p>Protocols can be extended to provide method and property implementations to conforming types. This allows you to define behavior on protocols themselves, rather than in each type’s individual conformance or in a global function.</p><pre>protocol SwitchableProtocol {<br>    var switchState: Bool { get }<br>}</pre><pre>extension SwitchableProtocol {<br>   var switchState: Bool { return true}<br>}</pre><p>Protocol extension can be used for providing default implementation within the protocol itself as explained in the previous section.</p><p>Also If a conforming type provides its own implementation of a required method or property, that implementation will be used instead of the one provided by the extension.</p><p><em>I hope this article provides a little bit clear overview of the swift Protocols. reference from apple developer docs and other blogs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebd1a8634198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Write Unit Test for Model Class]]></title>
            <link>https://medium.com/@raj.amsarajm93/swift-write-unit-test-for-model-class-8af05c175103?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/8af05c175103</guid>
            <category><![CDATA[xctest]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Tue, 28 Apr 2020 10:47:34 GMT</pubDate>
            <atom:updated>2020-04-28T10:47:34.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*xCpPAltTH58qj-UHD-pNNg.png" /></figure><p>This blog we are going to explore brief introduction to a Test Driven Development in iOS app development and will create a very basic unit test for Registration model struct.</p><p>For example we need to follow the Test Driven Development approach to implement the basic from validation logic. We will need to implement a class or struct to hold the provided user details and implement basic validation logic to make sure that the details valid or not.</p><h4>Test-Driven Development</h4><p>Test-Driven Development is a way of structuring our development process. if we not following the Test-Driven Development approach we will start write code first, after will start unit testing. In the test-driven development, we need to write a unit test first and then we can start to write app code to make the test case pass.</p><p>When we following Test-Driven development process for write a code, we need to follow 4 important steps that define the TDD life cycle: Red, Green, Refactor, Repeat. now we can explore about above mentioned four steps.</p><h4>1. Red</h4><p>In TDD process very initial step is red. It is called red is because the color of a failed unit test color code in Xcode is red. At this step before write app code, we need to create unit test case. That case will fail because we don’t have any app code. Once we have a failing unit test, the next step will be to write an app code for make this teat pass.</p><h4>2. Green</h4><p>The TDD life cycle next step is called Green. It is called Green because the color of passing unit test in Xcode is Green. This step we need to write a app code, to make our earlier written and failing unit test pass. Once unit test will pass the failing test color will change red to green.</p><h4>3. Refactor</h4><p>This step is called Refactor because at this step we need to clean up both our Unit test and app code for look and work good. Also we need to change constant to reusable methods. also need to avoid boiler plate code.</p><h4>4.Repeat</h4><p>The final step in the Test-Driven Development life cycle is called repeat. This means that we need to pick up a new feature and implement it by repeating the previous three steps. First we need to write failing unit test, then need to write app code to make unit test green, then we need to improve our unit test code and app code.</p><p>let’s have at very simple example of unit test that validates registration form data.</p><h4>Create sample Xcode Project</h4><p>We will start created very simple basic sample sample Xcode project. but one think we need to enable while creating project: we need to make sure that Unit testing is enabled for our project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yB4TQwW-cUmQMHGEM_GTlw.png" /></figure><p>if you are not enable unit test checkbox or already have existing project with no unit tests, we can always create a new unit test target and unit test class from Xcode navigator.</p><ol><li>First Switch to Test Navigator</li><li>Create a new unit test target and unit test class</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/538/1*MMPN101hK9LWtOniSSl1UQ.png" /></figure><p>We will give new Unit Test class a Name is UserFormModelTests.</p><p>Once we have a new unit test class created it will have some basic setup override methods from XCTestCase. The two important methods are <strong><em>setUp() </em></strong>method and the <strong><em>tearDown()</em></strong> method. other default methods we will delete. Once we delete that methods the test class will look like below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bK94-LTH20tEcm_K7q9-zg.png" /></figure><h4>Now we can start to follow Test-Driven Development life cycle:-</h4><p>first we need to create failing test method. Also, it is a good practices to write a minimum amount of code. Just enough for a test method to fail.</p><p>note that the name of the test method always must need to start with a <strong>test</strong> prefix. testUserFormModel_canCreateInstance().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sPJY10w5_Y2jKl4_S_OfPw.png" /></figure><p>if we run this test method it will fail because we don’t have UserFormModel. We completed TDD first step.</p><p>Now we can move second step in TDD life cycle Green. in Green need to start write app code and need to make fail test to pass. So we will create UserFormModel struct in our project.</p><pre><strong>import</strong> Foundation</pre><pre><strong>struct</strong> UserFormModel {</pre><pre><strong>   let</strong> firstName: String<br>   <strong>let</strong> lastName: String<br>   <strong>let</strong> email: String<br>}</pre><p>if we try to run our test case. it will pass.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*897rs9DS7KfP0x7bUw3Ihw.png" /></figure><p>Now we can move third and fourth steps</p><p>At third step is Refactor. Above example code nothing is very important that i see improve in. this methods at this moment. So we will move next step.</p><p>The next step is to pick up the next functionality that makes sense to work on and repeat the 3 steps again.</p><p>Added some more test methods:</p><pre><strong>func</strong> testUserFormModel_ShouldPassIfValidateFirstName() {</pre><pre><strong>      let</strong> unserModel = UserFormModel(firstName: &quot;Raj&quot;,</pre><pre>                       lastName: &quot;Mari&quot;,</pre><pre>                       email: &quot;xx@gmail.com&quot;)</pre><pre>     XCTAssertTrue(unserModel.isValidFirstName())</pre><pre>}</pre><pre><strong>func</strong> testUserFormModel_ShouldPassIfValidateLastName() {</pre><pre><strong>      let</strong> unserModel = UserFormModel(firstName: &quot;Raj&quot;,</pre><pre>                      lastName: &quot;Mari&quot;,</pre><pre>                      email: &quot;xx@gmail.com&quot;)</pre><pre>      XCTAssertTrue(unserModel.isValidLastName())</pre><pre>}</pre><pre><strong>func</strong> testUserFormModel_ShouldPassIfValidateEmail() {</pre><pre><strong>    let</strong> unserModel = UserFormModel(firstName: &quot;Raj&quot;,</pre><pre>                     lastName: &quot;Mari&quot;,</pre><pre>                     email: &quot;xx@gmail.com&quot;)</pre><pre>   XCTAssertTrue(unserModel.isValidEmail())</pre><pre>}</pre><pre><strong>func</strong> testUserFormModel_ShouldPassIfNotValidateEmail() {</pre><pre><strong>      let</strong> unserModel = UserFormModel(firstName: &quot;Raj&quot;,</pre><pre>                      lastName: &quot;Mari&quot;,</pre><pre>                       email: &quot;xxxxxx&quot;)</pre><pre>       XCTAssertFalse(unserModel.isValidEmail())</pre><pre>}</pre><p>UserFormModel.swift</p><pre><strong>extension</strong> UserFormModel {</pre><pre><strong>   func</strong> isValidFirstName() -&gt; Bool {</pre><pre><strong>        return</strong> firstName.count &gt; 1</pre><pre>   }</pre><pre><strong>   func</strong> isValidLastName() -&gt; Bool {</pre><pre><strong>       return</strong> firstName.count &gt; 1</pre><pre>   }</pre><pre><strong>   func</strong> isValidEmail() -&gt; Bool {</pre><pre><strong>         let</strong> emailRegEx = &quot;[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}&quot;</pre><pre><strong>         let</strong> emailPred = NSPredicate(format:&quot;SELF MATCHES %@&quot;, emailRegEx)</pre><pre><strong>         return</strong> emailPred.evaluate(with: email)</pre><pre> }</pre><pre>}</pre><p><em>I hope this article provides a little bit clear overview of the Unit Testing in iOS. I will share soon this sample project in github </em><a href="https://github.com/Raj-Sai?tab=repositories"><strong><em>here</em></strong></a><em>. Thanks</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8af05c175103" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android : Basic Fragment Tutorial]]></title>
            <link>https://medium.com/@raj.amsarajm93/android-basic-fragment-tutorial-ea5ed94e859d?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5ed94e859d</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[fragments]]></category>
            <category><![CDATA[fragment-lifecycle]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Sat, 25 Apr 2020 09:20:51 GMT</pubDate>
            <atom:updated>2020-04-25T16:09:06.398Z</atom:updated>
            <content:encoded><![CDATA[<h3>Android : Basic Fragment Tutorial</h3><p>In this Android Fragments with Java tutorial we will learn the fundamental concepts of fragments while creating an app that displays list and details based on destination device.</p><h4>Fragments:</h4><p>A Fragment represents a behaviour or a portion of user interface in a FragmentActivity. we can combine multiple fragments in single activity. Also we can build a multi-pane UI and reuse same fragment in multiple activities. This fragment having own lifecycle, receive its own input events, and which we can add or remove while the activity is running.</p><p>A fragment must always be hosted in an activity and the fragment’s lifecycle is directly affected by the host activity’s lifecycle. For example, when the activity is paused the fragments also in pause state, and when activity is destroyed the all fragment are destroyed. While an activity is running, we can manipulate each fragment independently, such as add or remove them. Also when we perform fragment transaction we can also add it to a back stack that will be managed by activity. it will help us for back button press(navigate to previous fragment). if not required navigation for fragment we can ignore back stack.</p><h4>Fragment life cycle:</h4><p>Like an activity, a fragment has a lifecycle with events that occur when the fragment’s status changes. For instance, an event happens when the fragment becomes visible and active, or when the fragment becomes unused and is removed. You can also add code and behaviours to callbacks for these events as you would for an activity.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*5xJfH0P4aUVAK_OFlHVCZA.png" /></figure><p>The following lifecycle events come into play when you add a fragment:</p><ul><li>onAttach: The fragment attaches to its host activity.</li><li>onCreate: A new fragment instance initialises, which always happens after it attaches to the host.</li><li>onCreateView: A fragment creates its portion of the view hierarchy, which is added to its activity’s view hierarchy.</li><li>onActivityCreated: The fragment’s activity has finished its own onCreate event.</li><li>onStart: The fragment is visible.</li><li>onResume: The fragment is visible and intractable.</li><li>onPause: The fragment is no longer intractable. This occurs when either the fragment is about to be removed or replaced or when the fragment’s activity pauses.</li><li>onStop: The fragment is no longer visible. This occurs either after the fragment is about to be removed or replaced or when the fragment’s activity stops.</li><li>onDestroyView: The view and related resources created in onCreateView are removed from the activity’s view hierarchy and destroyed.</li><li>onDestroy: The fragment does its final clean up.</li><li>onDetach: The fragment is detached from its activity.</li></ul><h4>Sample:</h4><p>here’s an example of an activity using two fragments to create a two-pane layout. The activity below includes one fragment to show a list of Shakespeare play titles and another to show a summary of the play when selected from the list. It also demonstrates how to provide different configurations of the fragments, based on the screen configuration.</p><pre>&lt;<strong>LinearLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:orientation=&quot;horizontal&quot;</strong>&gt;<br><br>    &lt;<strong>FrameLayout<br>        android:id=&quot;@+id/frame&quot;<br>        android:layout_width=&quot;0px&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot; </strong>/&gt;<br><br>    &lt;<strong>FrameLayout<br>        android:id=&quot;@+id/details&quot;<br>        android:layout_width=&quot;0px&quot;<br>        android:layout_height=&quot;match_parent&quot;<br>        android:layout_weight=&quot;1&quot;<br>        android:background=&quot;?android:attr/detailsElementBackground&quot; </strong>/&gt;<br>&lt;/<strong>LinearLayout</strong>&gt;</pre><p>Using this layout, the system instantiates the TitlesFragment (which lists the play titles) as soon as the activity loads the layout, while the <a href="https://developer.android.com/reference/android/widget/FrameLayout">FrameLayout</a> (where the fragment for showing the play summary appears) consumes space on the right side of the screen, but remains empty at first. As you&#39;ll see below, it&#39;s not until the user selects an item from the list that a fragment is placed into the <a href="https://developer.android.com/reference/android/widget/FrameLayout">FrameLayout</a>.</p><p>However, not all screen configurations are wide enough to show both the list of plays and the summary, side by side. So, the layout above is used only for the landscape screen configuration, by saving it at res/layout-land/fragment_layout.xml.</p><p>Thus, when the screen is in portrait orientation, the system applies the following layout, which is saved at res/layout/fragment_layout.xml:</p><pre>&lt;<strong>FrameLayout xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    android:layout_width=&quot;match_parent&quot;<br>    android:layout_height=&quot;match_parent&quot;<br>    android:id=&quot;@+id/frame&quot;</strong>&gt;<br><br>&lt;/<strong>FrameLayout</strong>&gt;</pre><p>So above we completed layout design part both landscape and normal screens. now we can move to implement activity and fragments.</p><p>First we can create ManiActivity.java file</p><p>when initial we come to this activity we are adding title fragment also if we rotate device we will get notification in onConfigurationChanged callback method.</p><pre>@Override<br><strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>    <strong>super</strong>.onCreate(savedInstanceState);<br><br>    setContentView(R.layout.<strong><em>fragment_layout</em></strong>);<br><br>    TitlesFragment fragment = <strong>new </strong>TitlesFragment();<br>    getSupportFragmentManager().beginTransaction()<br>            .replace(R.id.<strong><em>frame</em></strong>, fragment)<br>            .commit();<br>}<br><br>@Override<br><strong>public void </strong>onConfigurationChanged(Configuration newConfig) {<br>    <strong>super</strong>.onConfigurationChanged(newConfig);<br>    setContentView(R.layout.<strong><em>fragment_layout</em></strong>);<br>    TitlesFragment fragment = <strong>new </strong>TitlesFragment();<br>    getSupportFragmentManager().beginTransaction()<br>            .replace(R.id.<strong><em>frame</em></strong>, fragment)<br>            .commit();<br>}</pre><p>Next, we can see how this is accomplished in the fragment classes. First is TitlesFragment, which shows the list of Shakespeare play titles. This fragment extends <a href="https://developer.android.com/reference/android/app/ListFragment">ListFragment</a> and relies on it to handle most of the list view work.</p><pre><strong>public class </strong>TitlesFragment <strong>extends </strong>ListFragment {<br>    <strong>boolean mDualPane</strong>;<br>    <strong>int mCurCheckPosition </strong>= 0;<br><br>    @Override<br>    <strong>public void </strong>onActivityCreated(Bundle savedInstanceState) {<br>        <strong>super</strong>.onActivityCreated(savedInstanceState);<br><br>        setListAdapter(<strong>new </strong>ArrayAdapter&lt;String&gt;(getActivity(),<br>                android.R.layout.<strong><em>simple_list_item_activated_1</em></strong>, Shakespeare.<strong><em>TITLES</em></strong>));<br><br>        View detailsFrame = getActivity().findViewById(R.id.<strong><em>details</em></strong>);<br>        <strong>mDualPane </strong>= detailsFrame != <strong>null </strong>&amp;&amp; detailsFrame.getVisibility() == View.<strong><em>VISIBLE</em></strong>;<br><br>        <strong>if </strong>(savedInstanceState != <strong>null</strong>) {<br>            <strong>mCurCheckPosition </strong>= savedInstanceState.getInt(<strong>&quot;curChoice&quot;</strong>, 0);<br>        }<br><br>        <strong>if </strong>(<strong>mDualPane</strong>) {<br>            getListView().setChoiceMode(ListView.<strong><em>CHOICE_MODE_SINGLE</em></strong>);<br>            showDetails(<strong>mCurCheckPosition</strong>);<br>        }<br>    }<br><br>    @Override<br>    <strong>public void </strong>onSaveInstanceState(Bundle outState) {<br>        <strong>super</strong>.onSaveInstanceState(outState);<br>        outState.putInt(<strong>&quot;curChoice&quot;</strong>, <strong>mCurCheckPosition</strong>);<br>    }<br><br>    @Override<br>    <strong>public void </strong>onListItemClick(ListView l, View v, <strong>int </strong>position, <strong>long </strong>id) {<br>        showDetails(position);<br>    }<br><br>    <strong>void </strong>showDetails(<strong>int </strong>index) {<br>        <strong>mCurCheckPosition </strong>= index;<br><br>        <strong>if </strong>(<strong>mDualPane</strong>) {<br>            getListView().setItemChecked(index, <strong>true</strong>);<br><br>            DetailsFragment details = (DetailsFragment)<br>                    getFragmentManager().findFragmentById(R.id.<strong><em>details</em></strong>);<br>            <strong>if </strong>(details == <strong>null </strong>|| details.getShownIndex() != index) {<br>                details = DetailsFragment.<em>newInstance</em>(index);<br><br>                FragmentTransaction ft = getFragmentManager().beginTransaction();<br>                <strong>if </strong>(index == 0) {<br>                    ft.replace(R.id.<strong><em>details</em></strong>, details);<br>                } <strong>else </strong>{<br>                    ft.replace(R.id.<strong><em>details</em></strong>, details);<br>                }<br>                ft.setTransition(FragmentTransaction.<strong><em>TRANSIT_FRAGMENT_FADE</em></strong>);<br>                ft.commit();<br>            }<br><br>        } <strong>else </strong>{<br>            Intent intent = <strong>new </strong>Intent();<br>            intent.setClass(getActivity(), DetailsActivity.<strong>class</strong>);<br>            intent.putExtra(<strong>&quot;index&quot;</strong>, index);<br>            startActivity(intent);<br>        }<br>    }<br>}</pre><p>The second fragment, DetailsFragment shows the play summary for the item selected from the list from TitlesFragment:</p><pre><strong>public class </strong>DetailsFragment <strong>extends </strong>Fragment {<br><br>    <strong>public static </strong>DetailsFragment newInstance(<strong>int </strong>index) {<br>        DetailsFragment f = <strong>new </strong>DetailsFragment();<br><br>        Bundle args = <strong>new </strong>Bundle();<br>        args.putInt(<strong>&quot;index&quot;</strong>, index);<br>        f.setArguments(args);<br><br>        <strong>return </strong>f;<br>    }<br><br>    <strong>public int </strong>getShownIndex() {<br>        <strong>return </strong>getArguments().getInt(<strong>&quot;index&quot;</strong>, 0);<br>    }<br><br>    @Override<br>    <strong>public </strong>View onCreateView(LayoutInflater inflater, ViewGroup container,<br>                             Bundle savedInstanceState) {<br>        <strong>if </strong>(container == <strong>null</strong>) {<br>            <strong>return null</strong>;<br>        }<br><br>        ScrollView scroller = <strong>new </strong>ScrollView(getActivity());<br>        TextView text = <strong>new </strong>TextView(getActivity());<br>        <strong>int </strong>padding = (<strong>int</strong>) TypedValue.<em>applyDimension</em>(TypedValue.<strong><em>COMPLEX_UNIT_DIP</em></strong>,<br>                4, getActivity().getResources().getDisplayMetrics());<br>        text.setPadding(padding, padding, padding, padding);<br>        scroller.addView(text);<br>        text.setText(Shakespeare.<strong><em>DIALOGUE</em></strong>[getShownIndex()]);<br>        <strong>return </strong>scroller;<br>    }<br>}</pre><p>Recall from the TitlesFragment class, that, if the user clicks a list item and the current layout does <em>not</em> include the R.id.details view (which is where the DetailsFragment belongs), then the application starts the DetailsActivity activity to display the content of the item.</p><p>Here is the DetailsActivity, which simply embeds the DetailsFragment to display the selected play summary when the screen is in portrait orientation:</p><pre><strong>public class </strong>DetailsActivity <strong>extends </strong>AppCompatActivity {<br><br>    @Override<br>    <strong>protected void </strong>onCreate(Bundle savedInstanceState) {<br>        <strong>super</strong>.onCreate(savedInstanceState);<br><br>        <strong>if </strong>(getResources().getConfiguration().<strong>orientation<br>                </strong>== Configuration.<strong><em>ORIENTATION_LANDSCAPE</em></strong>) {<br>            finish();<br>            <strong>return</strong>;<br>        }<br><br>        <strong>if </strong>(savedInstanceState == <strong>null</strong>) {<br>            DetailsFragment details = <strong>new </strong>DetailsFragment();<br>            details.setArguments(getIntent().getExtras());<br>            getSupportFragmentManager().beginTransaction().add(android.R.id.<strong><em>content</em></strong>, details).commit();<br>        }<br>    }<br>}</pre><p>Notice that this activity finishes itself if the configuration is landscape, so that the main activity can take over and display the DetailsFragment alongside the TitlesFragment. This can happen if the user begins the DetailsActivity while in portrait orientation, but then rotates to landscape (which restarts the current activity).</p><blockquote>I hope this article provides a little bit clear overview of the Android Fragments. Download this sample project <a href="https://github.com/Raj-Sai/FragmentSample.git"><strong>here</strong></a>. Thanks</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5ed94e859d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Define if let, Guard let and defer statements]]></title>
            <link>https://medium.com/@raj.amsarajm93/swift-define-if-let-guard-let-and-defer-statements-dd9fc309a3d9?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd9fc309a3d9</guid>
            <category><![CDATA[if-let]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[guard]]></category>
            <category><![CDATA[defer]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Tue, 03 Dec 2019 10:17:51 GMT</pubDate>
            <atom:updated>2019-12-03T10:17:51.396Z</atom:updated>
            <content:encoded><![CDATA[<h4>if let:</h4><p>if let is also one type of optional binding. Use optional binding to find out whether an optional contains a value, and if so, to make that value available as a temporary constant or variable</p><p>An optional binding for the <strong>if</strong> statement is as follows −</p><pre>if let value = optionalValue {<br>// use value<br>} else {<br>if optionalValue nil we can handle here<br>}</pre><p>Use <strong><em>if let</em></strong> for small number of variables unwrapping and value of unwrapped variable not required outside block scope.</p><p>Also instead of <strong><em>if let</em></strong> we can use <strong><em>if var</em></strong> also. if any case need to change value within a branching scope we can use <strong><em>if var.</em></strong></p><p>When we need to continue execution in the current enclosing scope if value is nil or other.</p><p>if any scope need to check multiple values same time it is having more boiler code like below</p><pre>if let name = userName {<br>if let password = userPassword {<br>// use name and password<br>} else {<br>// invalid password<br>}} else {<br>// invalid userName<br>}</pre><h4>guard let:</h4><p>The <strong><em>guard let </em></strong>statement, on the other hand, makes our code more readable and we can avoid boiler code. Readability and easy maintenance are extremely important, especially when working with other programmers. The <strong><em>guard let</em></strong> statement help us to avoid the complexity of numerous nested conditions as seen in the <strong><em>if let</em></strong> example above. Different from the <strong><em>if let</em></strong>, the <strong><em>guard let</em></strong> statement makes early exits possible with an emphasis on negative cases with errors rather than on positive cases. This means we can test negative cases earlier by running the guard’s else statement if the condition is NOT met, rather than wait for nested conditions to pass first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*ck_WiyTvGAxwdeXr00NgqQ.png" /></figure><p>Also we can avoid nested <strong><em>if let</em></strong> like below</p><pre><strong>let</strong> name: String? = “raj”</pre><pre><strong>let</strong> password: String? = “password”</pre><pre><strong>func</strong> test () {</pre><pre><strong>guard</strong> <strong>let</strong> userName = name, <strong>let</strong> userPassword = password <strong>else</strong> {</pre><pre>print(“failed validation”)</pre><pre><strong>return</strong></pre><pre>}</pre><pre>}</pre><p>One thing to note: each guard statement <strong>must</strong> always transfer control by exiting the scope it is in. More specifically, if the “guard” is used in functions, it would usually <strong>return</strong>, and in loops, it would <strong>break</strong> or <strong>continue</strong>.</p><h4><strong>Defer Statement:</strong></h4><p>You use a <strong><em>defer</em></strong> statement to execute a set of statements just before code execution leaves the current block of code. This statement lets you do any necessary cleanup that should be performed regardless of <em>how </em>execution leaves the current block of code—whether it leaves because an error was thrown or because of a statement such as <strong><em>return</em></strong> or <strong><em>break</em></strong>. For example, you can use a <strong><em>defer</em></strong> statement to ensure that file descriptors are closed and manually allocated memory is freed.</p><p>A <strong><em>defer</em></strong> statement defers execution until the current scope is exited. This statement consists of the <strong><em>defer</em></strong> keyword and the statements to be executed later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/656/1*fVCOcTkepYuk3vIWtuPVUw.png" /></figure><p>I hope you get little bit idea about above three topics. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd9fc309a3d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift : Grand Central Dispatch Tutorial]]></title>
            <link>https://medium.com/@raj.amsarajm93/swift-grand-central-dispatch-tutorial-37480f538133?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/37480f538133</guid>
            <category><![CDATA[background]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gcd]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[multithreading]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Wed, 27 Nov 2019 05:56:20 GMT</pubDate>
            <atom:updated>2019-11-27T05:56:20.601Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift : Grand Central Dispatch Tutorial</h3><p>In Swift we have few different options available for asynchronous programming. Now we are going to discuss about GCD. GCD also on of the leading asynchronous topic in swift iOS. GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects. Work submitted to dispatch queues are executed on a pool of threads fully managed by the system. No guarantee is made as to the thread on which a task executes.</p><p>Also GCD is an API provided by apple to allow you to manage concurrent operations in a smooth way multi tasking, in order to avoid stuck of your application and keep it always intractable for users. GCD having three different type of Queues like as</p><ol><li><em>The Main Queue</em></li><li><em>The Global Queue</em></li><li><em>Custom Queues</em></li></ol><h4>The Main Queue:</h4><p>We should not able perform UI related operations on a background queue or queue other than the main queue, the compiler will show a warning if we do so. We need the main queue to perform UI operations. We can use the main queue like below</p><pre><em>DispatchQueue.main.async {<br>   self.view.backgroundColor = UIColor.blue<br>  }</em></pre><h4>The Global Queue:</h4><p>This Queue is separated into 5 main types and a default type according to QoS(Quality of Service), from highest priority to lowest. QoS is an enum with specific cases, and by providing the proper QoS value upon the queue initialisation you specify the desired priority. If no QoS is defined, then a default priority is given by to the queue. The following list summarises the available QoS cases, also called <em>QoS classes</em>. The first class means the highest priority, the last one the lowest priority:</p><ul><li>userInteractive</li><li>userInitiated</li><li>default</li><li>utility</li><li>background</li><li>unspecified</li></ul><p>1- userInteractive : <em>Work is virtually instantaneous. Similar to main thread.<br></em>2- userInitiated : Work <strong>is</strong> nearly instantaneous, such <strong>as</strong> a few seconds or less.<br>3-<strong> </strong>default: don’t use it usually , the type will be inferred by the system<br>4- utility: Work takes a few seconds to a few minutes.<br>5- background: Work takes significant time, such <strong>as</strong> minutes or hours.</p><p>Both, utility and background threads should be used for heavy operations that needs time in order not to block the main thread. hsdhs sudfsidfh usfsaifh usdfiasfhisa diusadfisa iasidasidhgdwidiaw udaidhoasdoas dusaifdhoashd aiufai<br>You can simply call one as follows:</p><pre>DispatchQueue.global(qos: .background).async {<br>    <em>//do background thread here<br></em>}</pre><p>above way we can achieve other QoS also.</p><h4>Custom Queues:</h4><p>Custom queues are queues that you can create on your own and give whatever QOS and attributes you want</p><pre><strong>let</strong> concurrentQueue = DispatchQueue(label: “concurrentQueue”, qos: .background, attributes: .concurrent)</pre><pre><strong>let</strong> serialQueue = DispatchQueue(label: “serialQueue”, qos: .background)</pre><p>also we can able to use same time combined Queues like below while downloading image from URL.</p><pre>DispatchQueue.global(qos: .background).async {<br>     <strong>let</strong> image = downloadImage()</pre><pre>DispatchQueue.main.async {<br>    <strong>self</strong>.imageView.image = image<br>}<br>}</pre><pre><strong>func</strong> downloadImage() -&gt; UIImage {<br><em>//download image here<br></em><strong>return</strong> image<br>}</pre><p>As you can notice we do the heavy operation that can take a lot of time inside a background thread and then display the image inside an imageView using the main thread.</p><h4>Async VS Sync:</h4><p>As you saw in the example above we used the word async after each queue.<br>With GCD, you can dispatch a task either synchronously or asynchronously.<br>Sync means that no other task will start until the sync operation finishes , while Async will allow other tasks to start even if it didn’t finish yet.</p><p>Let us take a look at real world examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1005/1*BSS0qaTRS7X5wIVueTQQZQ.png" /></figure><h4>Conclusion:</h4><p>GCD is the simplest way to write a multitasking code on iOS. We can use this to move the heavy tasks on the background thread and reduce the load on the main thread. There are lots of topics to explore in GCD. I haven’t covered them all to keep this post simple and short but covered all the essentials have been covered.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37480f538133" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS : Add Biometric Authentication FaceID/TouchID using Swift]]></title>
            <link>https://medium.com/@raj.amsarajm93/ios-add-biometric-authentication-faceid-touchid-using-swift-a96d13115fbd?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/a96d13115fbd</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swif]]></category>
            <category><![CDATA[apple-touch-id]]></category>
            <category><![CDATA[biometric-authentication]]></category>
            <category><![CDATA[face-id]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Tue, 12 Nov 2019 07:32:58 GMT</pubDate>
            <atom:updated>2019-11-12T07:32:58.998Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS : Add Biometric Authentication FaceID/TouchID using Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*FNFCQfMnS1IfYqNTy14LRg.jpeg" /></figure><p>Now a day all application having Biometric Authentication. Because FaceID and TouchID can be used for apps to authenticate users information like login credential, in-app purchase and sharing information one to another applications. Also in Mobile security is playing very major and crucial role last couple of years. Many platforms are allowing device owners to verify their identity by TouchID, FaceID and voice recognition. So apple also improving their local authentication TouchID and FaceID. Here we are going to explore how to add FaceID and TouchID in our iOS applications.</p><p>First I am going to create simple application and will navigate to ViewController. Then need to import <strong>LocalAuthentication</strong> into our ViewController. This LocalAuthentication framework will give all access for TouchID and FaceID validation in our local application. After we need to create <strong>LAContext</strong> object it will give us UI for evaluating the authentication policies and access controls, managing credentials, and invalidating authentication contexts.</p><pre><strong>let</strong> localAuthenticationContext = LAContext()<br>localAuthenticationContext.localizedFallbackTitle = &quot;Use Passcode&quot;</pre><p>After creation of LAContext object we need to check policy. This <strong>LAPolicy </strong>having two types,</p><ul><li><strong>deviceOwnerAuthenticationWithBiometrics</strong>: It puts restriction to use only biometric authentication to authenticate the device owner.</li><li><strong>deviceOwnerAuthentication</strong>: It will allow the application to authenticate the device owner using biometric or the device password.</li></ul><p>Here we are going to use <strong>deviceOwnerAuthenticationWithBiometrics</strong>. This will allow users to fallback to any other authentication method implemented by developers like username and pin code etc.</p><pre><strong>if </strong>localAuthenticationContext.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &amp;authError) { </pre><pre>}</pre><p><strong>canEvalutePolicy</strong> is Boolean method it will return true or false. if user not enrolled TouchID or FaceID it will return false. So we can show some alert to users. If it is true we need to call evalutePolicy.</p><pre>localAuthenticationContext.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reasonString) { success, evaluateError <strong>in<br>if</strong> success {</pre><pre>} <strong>else</strong> {<br><strong>guard</strong> <strong>let</strong> error = evaluateError <strong>else</strong> {<br><strong>return<br></strong>}</pre><pre>print(<strong>self</strong>.evaluateAuthenticationPolicyMessageForLA(errorCode: error._code))<br>}<br>}</pre><p>if we call evalutePolicy method it will requests authentication from users with specified security policy and it will show authentication dialog contains a cancel button with default title. and one more before implementing authentication we need to add usage description in <strong>info.plist</strong> file.</p><pre><strong>&lt;key&gt;</strong>NSFaceIDUsageDescription<strong>&lt;/key&gt;</strong></pre><pre><strong>&lt;string&gt;</strong>Logging in with Face ID<strong>&lt;/string&gt;</strong></pre><p><strong><em>evalutePolicy</em></strong>: asynchronously evaluates an authentication policy</p><p><strong><em>reasonString:- </em></strong>this is the reason for<strong><em> </em></strong>requesting authentication, which will be displayed to the user</p><p><strong><em>reply:- </em></strong>this is closure executed when evaluation finishes, which gives back success/failure and error if any with Error code</p><p>If evaluation success one can proceed with your further process, if not you can alt the user as he is unAuthorised.</p><p>I hope this article provides a little bit clear overview of the Add Authentication and As soon as possible i will share my code in GitHub. please check my <a href="https://github.com/Raj-Sai?tab=repositories"><strong><em>GitHub</em></strong></a> repositories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a96d13115fbd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: How to create Charts in iOS Application]]></title>
            <link>https://medium.com/@raj.amsarajm93/swift-how-to-create-charts-in-ios-application-3c58efa98561?source=rss-907b6a94da27------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c58efa98561</guid>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[charts]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Amsaraj Mariyappan]]></dc:creator>
            <pubDate>Fri, 25 Oct 2019 09:11:54 GMT</pubDate>
            <atom:updated>2019-10-25T09:14:33.752Z</atom:updated>
            <content:encoded><![CDATA[<p>Now a days many iOS application having one of the remarkable feature <strong>Graphs</strong>. So in this tutorial, we will show how to create charts in our application. Here we are going to create three different type of graphs line charts, pie chart and bar charts.</p><h4>Introduction</h4><p>We have many libraries that support displaying charts and one of them is <strong>Charts</strong> library and here i am going to use this library. Now we can open Xcode and create <strong>ChartsDemo</strong> Xcode project. After create project we need to add dependency library, we can add different ways like manual download, pod install and Carthage. Here I am going to use Pod installation. So we need to create pod file for pod install. we can use following command for pod file create <strong><em>pod ini</em>t. </strong>pod file has created after this we can view pod file using following command <strong><em>vi Podfile</em></strong>. now we can add <strong><em>pod Charts</em></strong> in Podfile. after add this pod we can install. after installation done need to open ChartsDemo.xcworkspace.<strong> </strong>After open project add four ViewController like below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*-R7hSRE4psm0_HR7m9bfpA.png" /></figure><p>First we can add three different button in HomeViewController and add each button segue show for different storyboard reference like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*UZuw1A-Sy16JzV_pq9TZFA.png" /></figure><p>Then run our application and test navigation it is working as per our requirement. if it works well we can start design chart design. First i am going to start <strong>BarChart</strong> design.</p><h4><strong>BarChart</strong></h4><p>Open BarChartStoryboard user interface then add View object to our storyboard. after adding view don’t forget to add auto layout constraint. and add custom <strong>BarChartView</strong> class as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/530/1*_5mb8Hx5tchQTFq5GWCXSw.png" /></figure><p>After that, we need to drag an <strong><em>IBOutlet</em></strong> connection from the <strong><em>View</em></strong> on the screen to the <strong>BarChartViewController</strong> that manages the <strong>BarChartView</strong>. Keep in mind to import the <em>Charts</em> library in order for the code to compile successfully. I have build our application it is working as per our need. Then we can create MockData class for chart. in MockData class i am going to add some cricket player list with them random hundreds list like below.</p><pre><strong>let</strong> players = [“K.S. Williamson”, “S.P.D. Smith”, “V. Kohli”, “Sachin”, “J.J. Bumrah”, “R.A. Jadeja”]<br><strong>let</strong> hundreds = [6, 8, 26, 30, 8, 10]</pre><p>Then, we are going to create a function displaying all these data and put it inside <em>viewDidLoad()</em> like this</p><pre>barChartData(playerList: players, values: hundreds.map { Double($0) })</pre><p>in viewDidLoad method inside setup our barChart animate, pinchZoomEnabled and etc.</p><pre>barChartView.animate(yAxisDuration: 2.0)<br>barChartView.pinchZoomEnabled = <strong>false<br></strong>barChartView.drawBarShadowEnabled = <strong>false<br></strong>barChartView.drawBordersEnabled = <strong>false<br></strong>barChartView.doubleTapToZoomEnabled = <strong>false<br></strong>barChartView.drawGridBackgroundEnabled = <strong>true</strong></pre><p>after setup now we can move to show barChart setup inside <strong>barChartData(…)</strong> method.</p><pre>barChartView.noDataText = “No Data available for Chart”<br><strong>var</strong> dataEntries: [BarChartDataEntry] = []</pre><pre><strong>for</strong> i <strong>in</strong> 0..&lt;playerList.count {<br><strong>let</strong> dataEntry = BarChartDataEntry(x: Double(i), y: Double(values[i]))<br>dataEntries.append(dataEntry)<br>}</pre><pre><strong>let</strong> chartDataSet = BarChartDataSet(entries: dataEntries, label: “Bar Chart View”)<br><strong>let</strong> chartData = BarChartData(dataSet: chartDataSet)<br>barChartView.data = chartData</pre><p>we done all setup now we can run our application. after run I can able to see our barChart.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*44S0OJTEXhPKak49aOTJkw.png" /><figcaption>barChart</figcaption></figure><p>Other charts as well same need to do first add View object in respective storyboard and add outlet for our ViewController, then get mock data and send that data to respective chart setups.</p><h4><strong>LineChart</strong></h4><pre><strong>var</strong> dataEntries: [ChartDataEntry] = []<br><strong>for</strong> i <strong>in</strong> 0..&lt;dataPoints.count-1 {<br><strong>let</strong> dataEntry = ChartDataEntry(x: values[i], y: Double(i))<br>dataEntries.append(dataEntry)<br>}</pre><pre><strong>let</strong> lineChartDataSet = LineChartDataSet(entries: dataEntries, label: <strong>nil</strong>)<br><strong>let</strong> lineChartData = LineChartData(dataSet: lineChartDataSet)<br>lineChartView.data = lineChartData</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*kZJLXJ1ghvgARVJpnwrthA.png" /></figure><h4><strong>PieChart</strong></h4><pre><em>// 1. Set ChartDataEntry<br></em><strong>var</strong> dataEntries: [ChartDataEntry] = []<br><strong>for</strong> i <strong>in</strong> 0..&lt;player.count {<br><strong>let</strong> dataEntry = PieChartDataEntry(value: values[i], label: player[i], data: player[i] <strong>as</strong> AnyObject)<br>dataEntries.append(dataEntry)<br>}</pre><pre><em>// 2. Set ChartDataSet<br></em><strong>let</strong> pieChartDataSet = PieChartDataSet(entries: dataEntries, label: <strong>nil</strong>)<br>pieChartDataSet.colors = colorsOfCharts(numbersOfColor: player.count)</pre><pre><em>// 3. Set ChartData<br></em><strong>let</strong> pieChartData = PieChartData(dataSet: pieChartDataSet)<br><strong>let</strong> format = NumberFormatter()<br>format.numberStyle = .none<br><strong>let</strong> formatter = DefaultValueFormatter(formatter: format)<br>pieChartData.setValueFormatter(formatter)</pre><pre><em>// 4. Assign it to the chart’s data<br></em>pieChartView.data = pieChartData</pre><ol><li>For each player and the hundreds he has, we set it to PieChartDataEntry object — a subclass of ChartDataEntry. Then we save it inside an array of PieChartDataEntry type.</li><li>The PieChartDataSet — a subclass of ChartDataSet will use this array to custom how to display them on the screen. For example, this line of codepieChartDataSet.colors will set colors for each part.</li><li>The PieChartData — a subclass of ChartData will store the PieChartDataSet. At this point, you can change the format of values which will be shown on the screen such as 15 instead of 15.0.</li><li>After we have done setting up everything, we assign the pieChartData to pieChartView.data</li><li>then we need to select some random colour for each players.</li></ol><pre><strong>for</strong> <strong>_</strong> <strong>in</strong> 0..&lt;numbersOfColor {<br>   <strong>let</strong> red = Double(arc4random_uniform(256))<br>   <strong>let</strong> green = Double(arc4random_uniform(256))<br>   <strong>let</strong> blue = Double(arc4random_uniform(256))<br>   <strong>let</strong> color = UIColor(red: CGFloat(red/255), green:   CGFloat(green/255), blue: CGFloat(blue/255), alpha: 1)<br>   colors.append(color)<br>}</pre><p>after finish coding part we can run our application we can see our pie charts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*CM8ZnoCuYbWin6WOTxZskQ.png" /></figure><h4>Conclusion</h4><p>I hope this article provides a little bit clear overview of the iOS Charts. I think here after we can able easily make beautiful and attractive charts using Charts dependency. As soon as possible i will share my code in GitHub. please check my <a href="https://github.com/Raj-Sai?tab=repositories"><strong><em>GitHub</em></strong></a> repositories.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c58efa98561" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>