<?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 Abhishek Thapliyal on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Thapliyal on Medium]]></description>
        <link>https://medium.com/@abhishekthapliyal?source=rss-77bba74aca88------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*4NURbN0gIdYVuRpmlT5rSA.jpeg</url>
            <title>Stories by Abhishek Thapliyal on Medium</title>
            <link>https://medium.com/@abhishekthapliyal?source=rss-77bba74aca88------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:16:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhishekthapliyal/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[iOS Swift Data: Generic Wrapper]]></title>
            <link>https://medium.com/@abhishekthapliyal/ios-swift-data-generic-wrapper-013734f0ae4a?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/013734f0ae4a</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[generics]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Fri, 02 Aug 2024 05:18:14 GMT</pubDate>
            <atom:updated>2024-08-02T13:02:03.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PZPOaSaLK__Qxbr8YOAXeQ.png" /></figure><p>Swift Data framework was introduced in <a href="https://developer.apple.com/videos/play/wwdc2023/10187/"><strong>WWDC 23</strong></a><strong> </strong>and added some updates in<strong> </strong><a href="https://developer.apple.com/videos/play/wwdc2024/10137/"><strong>WWDC 24</strong></a>. If you are aware of Core Data in <strong>UIKit</strong> then it will be easier to understand that the Swift Data in case of <strong>SwiftUI</strong>. Before launching <strong>Swift Data</strong> we were creating wrapper around <strong>Core Data</strong> and adding publishers to get updates but apple made things very easy and a bit tricky as well. As we go deep down we can see things are happening inside a view. Let’s dive in to get an idea.</p><p>Here we will walk through with an example application of employees which do basic operations <strong>CRUD</strong> i.e. <strong>Create</strong>, <strong>Retrieve</strong>, <strong>Update</strong> and <strong>Delete </strong>respectively.</p><h4>Setup</h4><p>Create a new SwiftUI project i.e. <strong>SwiftDataDemo</strong> and update your <strong>SwiftDataDemoApp.swift</strong> file like below.</p><pre>import SwiftUI<br>import SwiftData<br><br>@main<br>struct SwiftDataDemoApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ContentView()<br>        }<br>        .modelContainer(for: [Employee.self])<br>    }<br>}</pre><p>So here we are doing three things</p><ol><li>Importing framework <strong>SwiftData</strong>.</li><li>Setting up schema via passing array of expected models <strong>[Employee.self]</strong>.</li><li>Setting up our model container with schema using modifier <strong>.modelContainer(for: [Employee.self])</strong>.</li></ol><h4>Model</h4><p>We will now add a model <strong>Employee </strong>with basic details as shown in code below. Here we will create <strong>primary key</strong> like we use to have in <strong>RDBMS </strong>using<strong> </strong><strong>@Attribute(.unique) </strong>annotation i.e. <strong>id</strong> will be the <strong>primary key</strong>.</p><pre>import Foundation<br>import SwiftData<br><br>@Model<br>final class Employee {<br>    @Attribute(.unique) var id: String<br>    var name: String<br>    var emailId: String<br>    var address: String?<br>    var contact: Int<br>    <br>    init(id: String, name: String, emailId: String, address: String? = nil, contact: Int) {<br>        self.id = id<br>        self.name = name<br>        self.emailId = emailId<br>        self.address = address<br>        self.contact = contact<br>    }<br>}</pre><p>All the properties in the class <strong>Employee</strong> will be treated as <strong>attributes</strong> like we have in <strong>Tables</strong> in <strong>RDBMS</strong> and we can have <strong>optional</strong> properties which can be <strong>nullable</strong>. <strong>@Model </strong>is used to identify class as Model class for Swift Data like we used to have <strong>NSManagedObject</strong> classes in <strong>Core Data</strong>.</p><p><strong>Note:</strong> <strong>@Model</strong> annotation conforms to <strong>Observable</strong> protocol. <strong>Observable</strong>protocol is part of <strong>Observations</strong> framework introduced in <a href="https://developer.apple.com/videos/play/wwdc2023/10149/"><strong>WWDC23</strong></a>. So when there is any change in model class, that will be refelected directly to UI.</p><p><strong>@Model</strong> annotation also conforms to <a href="https://developer.apple.com/documentation/swiftdata/persistentmodel"><strong>PersistentModel</strong></a> which is generic protocol for each <strong>@Model</strong> class that interacts with <strong>Swift Data</strong>.</p><h4>Operations</h4><p>Setup a list view of employee using <strong>@Query</strong> annotation which gives list and <strong>update</strong> UI if there is <strong>any change</strong> in the list item like the <strong>@Published</strong> or <strong>@State</strong> variable.</p><pre>import SwiftUI<br>import SwiftData<br><br>struct ContentView: View {<br>    @Environment(\.modelContext) private var context<br>    @Query(sort: \Employee.name, order: .forward) var employees: [Employee]<br>    <br>    var body: some View {<br>        VStack {<br>            ScrollView {<br>                ForEach(employees) { emp in<br>                    HStack {<br>                      VStack {<br>                          Text(emp.name)<br>                          Text(emp.emailId)<br>                          Text(emp.hrDepartment.salary.description)<br>                          Text(emp.hrDepartment.designation)<br>                      }<br>                      .padding()<br>                      Spacer()<br>                    }<br>                    .background(Color.white)<br>                    .onTapGesture(count: 2) {<br>                        self.delete(id: emp.id)<br>                    }<br>                }<br>            }<br>            HStack {<br>                Text(&quot;Employees&quot;)<br>                Spacer()<br>                Button {<br>                    self.addEmployee()<br>                } label: {<br>                    Text(&quot;ADD&quot;)<br>                        .padding()<br>                }<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><p><strong>@Query </strong>also takes arguments for <a href="https://www.hackingwithswift.com/articles/263/build-your-first-app-with-swiftui-and-swiftdata"><strong>predicate and sorting</strong></a> with order as per the real use case.</p><p>In the beginning, we added the modifier <strong>.modelContainer(for: [Employee.self])</strong>, which introduces the <strong>modelContext</strong> in <strong>SwiftUI</strong> environment which is equivalent to <strong>NSManagedObjectContext </strong>in<strong> Core Data </strong>and responsible for all the interaction with<strong> PersistentStores </strong>like above<strong> CRUD </strong>operations. We can add that environment variable in our views like</p><pre>@Environment(\.modelContext) private var context</pre><h4>1. Create</h4><p>We will add function <strong>addEmployee() </strong>that will create a dummy data in our employee table. Create a new employee class object and then call <strong>create(employee: employee)</strong>. In this method we are accessing environment variable <strong>context </strong>and call available method<strong> </strong><strong>insert(&lt;PersistentModel Object&gt;) </strong>in order <strong>insert</strong> an <strong>entity</strong> to <strong>Employee</strong> table.</p><pre>func addEmployee() {<br>    let employee = Employee(<br>        id: &quot;101&quot;,<br>        name: &quot;John Doe&quot;,<br>        emailId: &quot;john.doe@example.com&quot;,<br>        address: &quot;Palo Alto, CA, USA&quot;,<br>        contact: 1234567890<br>    )<br><br>    self.create(employee: employee)<br>}<br><br>// MARK: - CREATE<br>func create(employee: Employee) {<br>    do {<br>        context.insert(employee)<br>        try context.save()<br>    } catch {<br>        debugPrint(error)<br>    }<br>}</pre><p>Once the model added successfully it will reflect directly in list.</p><h4>2. Retrieve</h4><p>Update you UI for user input where it takes employee <strong>id </strong>as it is a unique parameter which helps in getting distinct results. We will add <strong>retrieve</strong> method, which takes <strong>id </strong>as parameter, in order to retrieve employee. It will optional as it might be possible that employee for certain <strong>id</strong> doesn’t exists.</p><pre>// MARK: - RETRIEVE<br>func retrieve(id: String) -&gt; Employee? {<br>    do {<br>        // Create a predicate<br>        let predicate = #Predicate&lt;Employee&gt; {<br>            $0.id == id<br>        }<br>        <br>        // Create a descriptor<br>        let descriptor = FetchDescriptor&lt;Employee&gt;(<br>            predicate: predicate<br>        )<br>        <br>        // Fetch results<br>        let results = try context.fetch(descriptor)<br>        <br>        return results.first<br>    } catch {<br>        debugPrint(error.localizedDescription)<br>    }<br>    <br>    return nil<br>}</pre><p>There will be three steps to fetch expected employee</p><ol><li><strong>Create a predicate: </strong>Use <a href="https://developer.apple.com/documentation/foundation/predicate"><strong>#Predicate</strong></a> macro which creates <strong>Predicate</strong> object which will be used for filtering logic.</li><li><strong>Create a descriptor:</strong> Use <a href="https://developer.apple.com/documentation/swiftdata/fetchdescriptor"><strong>FetchDescriptor</strong></a><strong> </strong>that will captures the request criteria. This will create a fetch request with <strong>predicate</strong> as parameter. We can also pass <a href="https://developer.apple.com/documentation/swiftdata/fetchdescriptor/sortby"><strong>sort parameter</strong></a> in order to sort results. You can also set batch limit by assigning value like <strong>descriptor.fetchLimit = 20</strong>.</li><li><strong>Fetch Results: </strong>With<strong>context.fetch(descriptor) </strong>we will get an array of <strong>employees</strong> and we will return first element of results via passing the <strong>descriptor</strong> object.</li></ol><p>In the end it will return <strong>nil</strong> in case any failure.</p><h4>3. Update</h4><p>In your UI create a edit screen and add below method in order to update the details of employee. This <strong>update </strong>kept generic since we don’t know what needs to be update at the time we have to update something. It will take three parameters</p><ol><li><strong>Id: </strong>To get employee object.</li><li><strong>path: </strong>for which employee property we need to update.</li><li><strong>value</strong>: updated value of that selected property.</li></ol><pre>// MARK: - UPDATE<br>@discardableResult<br>func update&lt;Value&gt;(<br>    id: String,<br>    path: ReferenceWritableKeyPath&lt;Employee, Value&gt;,<br>    value: Value<br>) -&gt; Bool {<br>    do {<br>        guard let employee = retrieve(name: name, emailId: emailId) else {<br>            return false<br>        }<br>        <br>        employee[keyPath: path] = value<br>        try context.save()<br>        <br>        return true<br>    } catch {<br>        debugPrint(error)<br>    }<br>    <br>    return false<br>}</pre><p>In our previous section we covered <strong>retrieve </strong>function that will be used in order to fetch that <strong>employee</strong> with given <strong>id. </strong>Then with the help of <strong>keypath</strong> we will assign the <strong>updated</strong> value and the <strong>important</strong> step we will <strong>save</strong> the operation performed via<strong> </strong><strong>context.save()</strong>. Hit the button and you will see the updated value in the list for which the action is performed. The function will return <strong>boolean</strong> value depending upon the <strong>success</strong> and <strong>failure</strong>.</p><p><strong>Note: </strong>We are using keypath type <strong>ReferenceWritableKeyPath </strong>since the model class is <a href="https://www.linkedin.com/pulse/types-keypath-swift-sergey-leschev"><strong>reference</strong></a> type and we have to update values. We can use <strong>KeyPath </strong>normally while reading data.</p><h4>4. Delete</h4><p>Last but not least delete operation. Add a button in you list item and call below function. The function takes single argument <strong>id </strong>and we will use same method<strong> </strong><strong>retrieve </strong>and add <strong>context.delete(employee) </strong>in order to <strong>delete</strong> employee. That will also reflect in UI instantly. The function will return <strong>boolean</strong> value depending upon the <strong>success</strong> and <strong>failure</strong>.</p><pre>// MARK: - DELETE<br>@discardableResult<br>func delete(id: String) -&gt; Bool {<br>    guard let employee = retrieve(id: id) else {<br>        return false<br>    }<br>    <br>    context.delete(employee)<br>    return true<br>}</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F17348343&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fschitts-creek-daniel-levy-david-rose-you-dont-think-i-know-that-i-know-that-gif-17348343&amp;image=https%3A%2F%2Fmedia.tenor.com%2F1z6cNEW0PvwAAAAN%2Fschitts-creek-daniel-levy.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bee70c2d5bd343810e8ae21859a5141/href">https://medium.com/media/3bee70c2d5bd343810e8ae21859a5141/href</a></iframe><h3>Ya Ya !!!</h3><h3>Wrapper</h3><p>Coming to our objective to create a wrapper since the above operations are bound to a single <strong>SwiftUI</strong> <strong>View </strong>or <strong>ViewModel</strong> class. What if there are more <strong>Models</strong> in our app we can’t duplicate code every where. So let’s find a solution.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F4425271&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fyawnface-gif-4425271&amp;image=https%3A%2F%2Fmedia.tenor.com%2FGLZUkFLcqeQAAAAN%2Fyawnface.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/19541ecc785c8eff8658b962047267e1/href">https://medium.com/media/19541ecc785c8eff8658b962047267e1/href</a></iframe><h3>Come come !!!</h3><h4>1. Singleton Manager</h4><p>Create a singleton class <strong>SwiftDataManager </strong>and add two properties<strong> </strong><strong>ModelContainer</strong> and <strong>ModelContext</strong>. Initialize these properties in init as shown below.</p><pre>final class SwiftDataManager {<br>    let context: ModelContext<br>    let container: ModelContainer<br>    <br>    static let shared = SwiftDataManager()<br>    <br>    private init() {<br>        do {<br>            container = try ModelContainer(for: Employee.self)<br>            context = ModelContext(container)<br>        } catch {<br>            fatalError(error.localizedDescription)<br>        }<br>    }<br>}</pre><p><strong>ModelContainer</strong> will intialize in same we have done in previous example. You can pass comma seperated values for more models in above <strong>not in array</strong>.</p><p><strong>ModelContext</strong> is same context object via container that we are going to use for our same four <strong>CRUD</strong> operations.</p><p><strong>Note: </strong>You can create <strong>Dependency Injection</strong> instead of Singleton or try <a href="https://swiftwithmajid.com/2024/07/09/introducing-entry-macro-in-swiftui/"><strong>Entry macro</strong></a> recently added in<strong> </strong><a href="https://developer.apple.com/documentation/SwiftUI/Entry()"><strong>WWDC24</strong></a>. I just added for quick demonstration. Same thing you can try adding the context in <strong>Environment</strong> for easy access if needed.</p><h4>2. Setup</h4><p>Add two typealiases <strong>DBModel</strong> and <strong>DBValue </strong>in manager class.</p><pre>typealias DBModel = PersistentModel<br>typealias DBValue = Comparable &amp; Decodable</pre><p><strong>PersistentModel</strong> is generic type that <strong>Swift Data</strong> undestand under the hood for any <strong>Model</strong> or <strong>Entity</strong> class. So just for distinction I have added <strong>DBModel</strong>.</p><p>Whatever the value we are going to pass to <strong>retrieve</strong> and <strong>update</strong> that should be type of <strong>DBValue</strong> as the <strong>Swift Data</strong> expects the value should be <strong>Comparable</strong> &amp; <strong>Decodable</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F15540257&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fthats-interesting-interesting-i-see-oic-really-gif-15540257&amp;image=https%3A%2F%2Fmedia.tenor.com%2FyYcVGgIIkLcAAAAN%2Fthats-interesting-interesting.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c87f41ab4b806a78a52baed318a1a97/href">https://medium.com/media/2c87f41ab4b806a78a52baed318a1a97/href</a></iframe><h3>Yep 😝 !!!</h3><h4>3. Extension</h4><p>Add extension for <strong>PersistentModel </strong>in manager class.</p><pre>extension PersistentModel {<br>   ...<br>}</pre><p>We are going to add our all four <strong>CRUD </strong>operartions one by one.</p><h4>4. Operations Again 😜</h4><p>We are going to use Swift generics in order to proceed.</p><h4><strong>4A. Create</strong></h4><p>Replace the older <strong>create</strong> method and add <strong>create </strong>by below one.</p><p><strong>Note:</strong> For the <strong>context</strong> we are going to use same <strong>context</strong> property mentioned in the <strong>manager</strong> class in here and later on.</p><pre>// MARK: - CREATE<br>static func create&lt;M&gt;(model: M) where M: DBModel {<br>    do {<br>        let context = SwiftDataManager.shared.context<br>        context.insert(model)<br>        try context.save()<br>    } catch {<br>        debugPrint(error)<br>    }<br>}</pre><p>Here the generic type <strong>&lt;M&gt;</strong> will be of <strong>DBModel</strong> type. Since our <strong>Employee</strong> class fills the criteria, you will see the previous employee list will updated on calling this. Below is the way you will call above function.</p><pre>func addEmployee() {<br>    let emp = Employee(<br>        id: &quot;200&quot;,<br>        name: &quot;Test Name&quot;,<br>        emailId: &quot;emailId@example.com&quot;,<br>        address: &quot;address City Country ZIP&quot;,<br>        contact: 1234567890<br>    )<br>    <br>    Employee.create(model: emp)    <br>}</pre><h4>4B. Retrieve</h4><p>Replace the older <strong>retrieve</strong> method and add <strong>retrieve </strong>by below one.</p><pre>// MARK: - RETRIEVE<br>static func retrieve&lt;M, V&gt;(<br>    path: KeyPath&lt;M, V&gt;,<br>    value: V<br>) -&gt; M? where M: DBModel, V: DBValue {<br>    do {<br>        <br>        // Create a predicate<br>        let predicate = Foundation.Predicate&lt;M&gt; { model in<br>            PredicateExpressions.build_Equal(<br>              lhs: PredicateExpressions.KeyPath(root: model, keyPath: path),<br>              rhs: PredicateExpressions.Value(value)<br>            ) as! any StandardPredicateExpression&lt;Bool&gt;<br>        }<br>   <br>        // Create a descriptor<br>        let descriptor = FetchDescriptor&lt;M&gt;(predicate: predicate)<br>        <br>        // Context<br>        let context = SwiftDataManager.shared.context<br>        <br>        // Results<br>        let results: [M] = try context.fetch(descriptor)<br>        <br>        return results.first<br>    } catch {<br>        debugPrint(error.localizedDescription)<br>    }<br>    <br>    return nil<br>}</pre><p>The new <strong>retrieve </strong>takes two arguments below</p><ol><li><strong>path: </strong>For which distinct value we are seeking of type <strong>KeyPath&lt;M, V&gt; </strong>with<strong> </strong><strong>M </strong>aka<strong> </strong><strong>DBModel</strong>.</li><li><strong>value: </strong>Value for respective keyPath of type <strong>V</strong> aka <strong>DBValue</strong>.</li></ol><p>Previously we created a predicate using macro but here we need to create manually as <strong>#Predicate </strong>macro <strong>doesn’t supports keypath</strong> operations directly. In this predicate we will compare two values using <a href="https://developer.apple.com/documentation/foundation/predicateexpression"><strong>PredicateExpressions</strong></a>.</p><ol><li><a href="https://fatbobman.com/en/posts/swift-predicate-usage-composition-and-considerations/"><strong>PredicateExpressions.build_Equal</strong></a><strong>:</strong> Will compare values provided in <strong>lhs</strong> and <strong>rhs</strong> arguments.</li><li><strong>lhs: </strong>Expression with keypath will take root model from outer closure argument.</li></ol><pre>Foundation.Predicate&lt;M&gt; { model in <br>   ...<br>}</pre><p>3. <strong>rhs: </strong>Expression with value will take the value from function argument to compare.</p><h4><strong>Note:</strong></h4><ol><li>In this we have to define generic model for which we are executing hence we <strong>define here and wherever</strong> required with <strong>&lt;M&gt;</strong> or <strong>&lt;M, V&gt;</strong>. Hence we added Generic Type <strong>&lt;M&gt;</strong> for <strong>predicate</strong>, <strong>descriptor</strong> and for <strong>results</strong>.</li><li>I didn’t find suitable solution for the predicate so here we have to type case predicate expression into <strong>any StandardPredicateExpression&lt;Bool&gt; .<br>Help me to get better solution as I don’t prefer force unwrapping and typecasting if there is an alternate available.</strong></li></ol><p>Whatever we <strong>&lt;M&gt; </strong>value type we will pass we will receive results array of type <strong>[M] </strong>and we will return the very first element. Hence we call above function like below</p><pre>if let model = Employee.retrieve(path: \Employee.id, value: &quot;200&quot;) {<br>    print(&quot;Employee:&quot;, model.name)<br>} else {<br>    print(&quot;Employee with this ID not present&quot;)<br>}</pre><h4>4C. Update</h4><p>In our previous section we covered generic <strong>retrieve </strong>function that will be used in order to fetch that <strong>employee</strong> with given <strong>id. </strong>We will be using same to update as well. Replace you previous <strong>update</strong> function with below.</p><pre>// MARK: - UPDATE    <br>static func update&lt;M, V, N&gt;(<br>    idPath: KeyPath&lt;M, V&gt;,<br>    idValue: V,<br>    targetPath: ReferenceWritableKeyPath&lt;M, N&gt;,<br>    targetValue: N<br>) where M: DBModel, V: DBValue, N: DBValue {<br>    do {<br>        guard let model = retrieve(path: idPath, value: idValue) else {<br>            throw ModelError.custom(<br>                message: &quot;Model with path: \(idPath) OR value: \(idValue) doesn&#39;t exist&quot;<br>            )<br>        }<br>        <br>        model[keyPath: targetPath] = targetValue<br>        <br>        let context = SwiftDataManager.shared.context<br>        try context.save()<br>    } catch {<br>        debugPrint(error.localizedDescription)<br>    }<br>}</pre><p>Here we take four arguments</p><ol><li><strong>idPath:</strong> For which we can fetching and filtering employee object.</li><li><strong>idValue: </strong>Value for <strong>idPath</strong> to match.</li><li><strong>targetPath: </strong>For which we have to update value.</li><li><strong>targetValue</strong>: Value for <strong>targetPath </strong>to update.</li></ol><p>We have used different generic type <strong>N</strong> for the value as it may be possible to have different data types for <strong>id</strong> and <strong>updating path value</strong> which gives compile time error if kept same.</p><p>We will get <strong>employee</strong> <strong>object</strong> from <strong>retrieve</strong> function and same as previous we will <strong>update</strong> value of that object via <strong>keypath</strong> and <strong>save</strong> the object. Hence we call above function like</p><pre>Employee.update(<br>    idPath: \Employee.id,<br>    idValue: &quot;200&quot;,<br>    targetPath: \Employee.name,<br>    targetValue: &quot;New Name&quot;<br>)</pre><p>As usual you employee list will get updated.</p><h4>4D. Delete</h4><p>In last we will replacing <strong>delete</strong> by the below function.</p><pre>// MARK: - DELETE<br>static func delete&lt;M, V&gt;(<br>    path: KeyPath&lt;M, V&gt;,<br>    value: V<br>) -&gt; M? where M: DBModel, V: DBValue {<br>    <br>    guard let model = retrieve(path: path, value: value) else {<br>        return nil<br>    }<br>    <br>    let context = SwiftDataManager.shared.context<br>    context.delete(model)<br>    <br>    return model<br>}</pre><p>The function take same <strong>keypath</strong> and the corresponding <strong>value</strong> as mentioned in the previous sections. Hence we call above function like</p><pre>if let model = Employee.delete(path: \Employee.id, value: emp.id) {<br>    print(&quot;Employee:&quot;, model.name)<br>} else {<br>    print(&quot;Employee with this ID not present&quot;)<br>}</pre><p>As usual you employee list will get updated.</p><h4>Closing Arguments</h4><p>This is not exact way creating a wrapper around models but at least gives an idea how we can start. I haven’t explored wrapper for <strong>relationship</strong> but i’m sure you guys can extend to add that as well. <strong>Home work</strong> <strong>is explore the migrations in Swift Data as well.</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F15551523&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fdollar-hotdogs-gif-15551523&amp;image=https%3A%2F%2Fmedia.tenor.com%2F-KWcmvpPUqYAAAAN%2Fdollar-hotdogs.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/591c7a711d3bf67906e6edc60ae2b5ff/href">https://medium.com/media/591c7a711d3bf67906e6edc60ae2b5ff/href</a></iframe><h3>Finally Ends 😮‍💨 !!!</h3><p>Hope you like this blog and get some idea about Swift Data. I have attached the references for source of encouragement and appreciating their efforts.</p><h3>Happy Coding 👋🏻 !!!</h3><h4>Reference Links:</h4><ol><li><a href="https://www.hackingwithswift.com/articles/263/build-your-first-app-with-swiftui-and-swiftdata">https://www.hackingwithswift.com/articles/263/build-your-first-app-with-swiftui-and-swiftdata</a></li><li><a href="https://developer.apple.com/documentation/swiftdata/persistentmodel">https://developer.apple.com/documentation/swiftdata/persistentmodel</a></li><li><a href="https://fatbobman.com/en/posts/swift-predicate-usage-composition-and-considerations/">https://fatbobman.com/en/posts/swift-predicate-usage-composition-and-considerations/</a></li><li><a href="https://www.avanderlee.com/swift/predicate-macro-filtering-searching/">https://www.avanderlee.com/swift/predicate-macro-filtering-searching/</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2023/10187/">https://developer.apple.com/videos/play/wwdc2023/10187/</a></li><li><a href="https://developer.apple.com/videos/play/wwdc2024/10137/">https://developer.apple.com/videos/play/wwdc2024/10137/</a></li><li><a href="https://developer.apple.com/documentation/foundation/predicate">https://developer.apple.com/documentation/foundation/predicate</a></li><li><a href="https://developer.apple.com/documentation/swiftdata/fetchdescriptor">https://developer.apple.com/documentation/swiftdata/fetchdescriptor</a></li><li><a href="https://www.linkedin.com/pulse/types-keypath-swift-sergey-leschev">https://www.linkedin.com/pulse/types-keypath-swift-sergey-leschev</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=013734f0ae4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS 18: Swift Testing]]></title>
            <link>https://medium.com/@abhishekthapliyal/ios-18-swift-testing-102c8d309185?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/102c8d309185</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-testing]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 12:04:56 GMT</pubDate>
            <atom:updated>2024-08-07T08:20:05.681Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>WWDC 24</strong> released new testing framework to write test cases called <a href="https://github.com/apple/swift-testing"><strong>Swift-Testing</strong></a>. Previously we were using <strong>XCTest</strong>. The new test APIs are easy and far better integrate. Let’s dive in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMP4K_DbKYI4hc5RoSt61g.png" /></figure><p><strong>Requirement:</strong> <strong>Xcode 16</strong> and <strong>iOS 18</strong><em> (Both beta as of now)</em></p><p>We will walk through most of the things with examples. Setup your project withe some <strong>APIClient</strong> using <strong>Combine</strong> or <strong>async/await</strong> operations.</p><h4>Login Regex and Validations</h4><p>In this we have two fields email and password and a login button that will validate and navigate to users screen. Email and password will be using regex validations.</p><pre>struct RegexStrings {<br>    /// Password must contain at least 8 characters, 1 uppercase, 1 number, and 1 special character.<br>    static var passwordRegex: String {<br>        let oneOrMoreUpperCase = &quot;(?=.*[A-Z])&quot;<br>        let oneOrMoreLowerCase = &quot;(?=.*[a-z])&quot;<br>        let oneOrMoreNumber = &quot;(?=.*[0-9])&quot;<br>        let oneOrMoreSpecials = &quot;(?=.*[!@#$%^&amp;*()_+=-])&quot;<br>        let lengthGreaterThan = &quot;{8,}&quot;<br>        return &quot;^\(oneOrMoreUpperCase)\(oneOrMoreLowerCase)\(oneOrMoreNumber)\(oneOrMoreSpecials).\(lengthGreaterThan)&quot;<br>    }<br>    <br>    /// Email predicate alphabet &amp; number more than one + @ +<br>    static var emailRegex: String {<br>        let firstpart = &quot;[A-Z0-9a-z]([A-Z0-9a-z._%+-]{0,30}[A-Z0-9a-z])?&quot;<br>        let serverpart = &quot;([A-Z0-9a-z]([A-Z0-9a-z-]{0,30}[A-Z0-9a-z])?\\.){1,5}&quot;<br>        return firstpart + &quot;@&quot; + serverpart + &quot;[A-Za-z]{2,6}&quot;<br>    }<br>}<br><br>extension String {<br>    func evaluate(regex: String) -&gt; Bool {<br>        let predicate = NSPredicate(format: &quot;SELF MATCHES %@&quot;, regex)<br>        return predicate.evaluate(with: self)<br>    }<br>}</pre><p>Email will support any acceptable format and password will have <strong>minimum one small, one CAPITAL, 1 numeric &amp; special character with “8” minimum characters</strong> required. <strong>String </strong>extension evaluate will be used for validations.</p><h4>Import Framework</h4><p>Now let’s add new file in test target or remove <strong>XCTest</strong> code in existing one. For latest testing framework will use framework <strong>Testing. </strong>We validation test will also be import target via<strong> </strong><strong>@testable import &lt;TargetName&gt;</strong></p><pre>import Testing<br>@testable import &lt;TargetName&gt;</pre><h4>Suite</h4><p>In the new framework, we can create different suites i.e. kind of groups depending upon the use case.</p><pre>@Suite(&quot;Login Credentials Validations Tests&quot;)</pre><p>Unlike <strong>XCTest </strong>we will create <strong>structs</strong> instead of <strong>classes </strong>as mentioned in the <a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest#Convert-test-classes"><strong>document</strong></a>.</p><pre>@Suite(&quot;Login Credentials Validations Tests&quot;)<br>struct ValidationTest {<br>  // Add your test cases<br>}</pre><h4>Test and Expect Macro</h4><p>Previously we have to add prefix <strong>test</strong> in order to determine function is a test one for compiler. Now we just need to add annotation <strong>@Test </strong>as shown below. The annotation take several arguments like lable and arguements as an array.</p><pre>@Test(<br>    &quot;Check various invalid emails&quot;,<br>    arguments: [<br>        &quot;abc@f.i&quot;,<br>        &quot;abc@.in&quot;,<br>        &quot;@.in&quot;,<br>        &quot;abc@fin&quot;,<br>        &quot;abc@fin.&quot;,<br>        &quot;abc+1@finco&quot;<br>    ]<br>)<br><br>func invalidEmails(args: String) {<br>    let isValid = args.evaluate(regex: RegexStrings.emailRegex)<br>    #expect(!isValid)<br>}</pre><p>In above test we added label <strong>“Check various invalid emails” </strong>and some invalid values as an array arguments. Now we have the <strong>#expect </strong>macro which requires a <strong>boolean</strong> value to pass or fail. Previously we have numerous of methods to specify to get same results.</p><pre>XCTAssertTrue()<br>XCTAssertFalse()<br>XCTAssertNil()<br>XCTAssertNotNil()<br>XCTAssertEqual()<br>XCTAssertGreaterThan()<br>... and so on</pre><p>On running above sample test <strong>isValid </strong>becomes <strong>false</strong> and hence our expectation will be fullfilled. Now as we have to consider the valid email cases so we have to write test cases for same as well. With same approach the valid test case method will be</p><pre>@Test(<br>    &quot;Check various valid emails&quot;,<br>    arguments: [<br>        &quot;abc@f.in&quot;,<br>        &quot;abc+1@fin.co&quot;,<br>        &quot;abc.zyx@cc.com&quot;,<br>        &quot;abc12_zyx@cc.com&quot;<br>    ]<br>)<br>func validEmails(args: String) {<br>    let isValid = args.evaluate(regex: RegexStrings.emailRegex)<br>    #expect(isValid)<br>}</pre><p>On running above sample test <strong>isValid </strong>becomes <strong>true</strong> and hence our expectation will be fullfilled. <strong>Try for password with given regex at the beginning.</strong></p><h4>Arguments</h4><p>We can also write test cases with more than one collection.</p><pre>@Test(<br>    &quot;Check various credentials&quot;,<br>    arguments: [&quot;abc+1@fin.co&quot;, &quot;abc.zyx@cc.com&quot;], [&quot;abcd123@!AA&quot;, &quot;sss121BB@AA&quot;]<br>)<br>func validateCredentails(email: String, password: String) {<br>    let isValidEmail = email.evaluate(regex: RegexStrings.emailRegex)<br>    let isValidPassword = password.evaluate(regex: RegexStrings.passwordRegex)<br>    let isValid = isValidEmail &amp;&amp; isValidPassword<br>    #expect(isValid)<br>}</pre><p>Test annotation also support multiple arguments up to two collections in way that whole combination will be of <strong>2 x 2 = 4</strong> test cases i.e. for each email we will have all the passwords in second collection.</p><p>Some time it may takes time longer than usual and execute unnecessary cases. In order to fix that use <a href="https://developer.apple.com/documentation/swift/zip(_:_:)"><strong>zip</strong></a>. Hence the first email will be bind with first password and so on.</p><pre>@Test(<br>    &quot;Check various credentials&quot;,<br>    arguments: zip([&quot;abc+1@fin.co&quot;, &quot;abc.zyx@cc.com&quot;], [&quot;abcd123@!AA&quot;, &quot;sss121BB@AA&quot;])<br>)<br>func validateCredentails(email: String, password: String) {<br>    let isValidEmail = email.evaluate(regex: RegexStrings.emailRegex)<br>    let isValidPassword = password.evaluate(regex: RegexStrings.passwordRegex)<br>    let isValid = isValidEmail &amp;&amp; isValidPassword<br>    #expect(isValid)<br>}</pre><p>As mentioned the output will be</p><pre>◇ Passing 2 arguments email → &quot;abc+1@fin.co&quot;, password → &quot;abcd123@!AA&quot; to &quot;Check various credentials&quot;<br>◇ Passing 2 arguments email → &quot;abc.zyx@cc.com&quot;, password → &quot;sss121BB@AA&quot; to &quot;Check various credentials&quot;</pre><p><strong>Note:</strong> Previously we have two overridden methods that called for each test cases.</p><pre>override func setUpWithError() throws {<br>    // Put setup code here. This method is called before the invocation of each test method in the class.<br>}<br><br>override func tearDownWithError() throws {<br>    // Put teardown code here. This method is called after the invocation of each test method in the class.<br>}</pre><p>Now we can use <strong>struct</strong> <strong>init</strong> and <strong>deinit</strong> to achieve same functionality as mentioned in the <a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest#Convert-setup-and-teardown-functions"><strong>document</strong></a>.</p><h4>Class and APIs</h4><p>As mentioned earlier we can create different suites hence for APIs we have <strong>API Validations</strong> suites. Now after validating credentials locally let’s validate from server side i.e. testing asynchronously. It’s obvious that in real world scenario we have some api calls to authenticate user so we assume an arbitrary call which works as expected.</p><pre>@Suite(&quot;API Validations&quot;)<br>final class APIValidations {<br>    <br>    private let apiClient: APIClient<br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        APIClientResolver.shared.mode = .mock<br>        apiClient = APIClientResolver.shared.apiClient<br>    }<br>    <br>    @Test(<br>        &quot;Check Login Credentials&quot;,<br>        arguments: zip([&quot;abc+1@fin.co&quot;, &quot;abc.zyx@cc.com&quot;], [&quot;abcd123@!AA&quot;, &quot;sss121BB@AA&quot;])<br>    )<br>    func login(emailId: String, password: String) {<br>        apiClient.login(emailId: emailId, password: password)<br>            .sink { completion in<br>                switch completion {<br>                case .finished:<br>                    break<br>                case .failure(let error):<br>                    #expect(error != nil)   // CallBack Here 2<br>                }<br>            } receiveValue: { result in<br>                #expect(result != nil)      // CallBack Here 1<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}</pre><p>Here we have used class instead as the APIs are implemented via <strong>AnyPublisher</strong> instead of <strong>async/await </strong>so that we can store <strong>cancellables</strong> if needed. Now if the credentials are authentic it will return to <br><strong>// CallBack Here 1 </strong>else<strong> </strong><strong>// CallBack Here 2</strong>.</p><h4>Asynchronous Operations</h4><p>There will be a time when we are going to use API calls using<strong>async/await</strong> operations. Hence we will write test cases for them as well.</p><pre>@Test(&quot;Get Users API&quot;)<br>func users() async throws {<br>    let result = try await apiClient.getUsers()<br>    switch result {<br>    case .success(let result):<br>        #expect(result.isEmpty)<br>    case .failure(let error):<br>        #expect(error != nil)<br>    }<br>}</pre><p><strong>Note: </strong>There are some cases in which you need to run tests in main thread. Hence we can add <strong>@MainActor </strong>annotation like we do in our latest concurrency. Also library supports <strong>async</strong>, <strong>throws and </strong><strong>async throws </strong>depending upon the use case.</p><pre>@Test(&quot;Get Users API&quot;)<br>@MainActor<br>func users() async throws {<br>    let result = try await apiClient.getUsers()<br>    switch result {<br>    case .success(let result):<br>        #expect(result.isEmpty)<br>    case .failure(let error):<br>        #expect(error != nil)<br>    }<br>}</pre><h4>Serialized</h4><p>By default all the tests run parallely but in case if we need to run tests in <strong>serialized</strong> way we use serialized trait.</p><pre>@Suite(&quot;Suite Label&quot;, .serialized)<br>@Test(&quot;Test Method Label&quot;, .serialized)</pre><h4>Issue and Require</h4><p>In above example if there is an error which is unexpected then we can also use <a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest#Record-issues"><strong>Issue.record(“&lt;Message&gt;”)</strong></a><strong> </strong>to record an unconditional issue.</p><pre>switch completion {<br>case .finished:<br>    break<br>case .failure(let error):<br>    Issue.record(error.description)<br>}</pre><p>Or if there is a dependency further and we want success state only to proceed so we can also use <strong>#</strong><a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest#Continue-or-halt-after-test-failures"><strong>require</strong></a> macro in order to hold test case. It takes a <strong>boolean</strong> argument to validate.</p><pre>@Test(&quot;Check Auth Token&quot;)<br>func checkAuthToken() async throws {<br>    let authToken = apiClient.authToken<br>    #require(authToken != nil)<br>}</pre><p>Here the test will be not proceed further for next test until <strong>#require</strong> condition is fulfilled. It also unwrap optional type to check nil value i.e. alternate to <a href="https://developer.apple.com/documentation/xctest/3380195-xctunwrap"><strong>XCTUnwrap</strong></a><strong>()</strong>.</p><pre>@Test(&quot;Check Auth Token&quot;)<br>func checkAuthToken() async throws {<br>    let authToken = apiClient.authToken<br>    #require(authToken)<br>}</pre><h4>TimeLimit</h4><p>New framework comes traits. One of them is <strong>timeLimit</strong>. Let say an function or an API takes longer then expected we can use this to test that as well.</p><pre>@Test(&quot;Test time limit&quot;, .timeLimit(.minutes(1)))<br>func users() async throws {<br>    let result = try await timeoutTest()<br>    switch result {<br>    case .success(let result):<br>        #expect(result.isEmpty)<br>    case .failure(let error):<br>        #expect(error != nil)<br>    }<br>}<br><br>func timeoutTest() async throws -&gt; Result&lt;[User], Error&gt; {<br>    try await Task.sleep(seconds: 65)<br>    return .failure(APIError.default)<br>}<br><br>extension Task where Success == Never, Failure == Never {<br>    static func sleep(seconds: Double) async throws {<br>        let duration = UInt64(seconds * 1_000_000_000)<br>        try await Task.sleep(nanoseconds: duration)<br>    }<br>}</pre><p>As of now timeLimit only accepts minutes so added <strong>1 minute</strong> to test and it will fail as it will take <strong>65 seconds</strong> to complete.</p><h4><a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/conditiontrait">ConditionTrait</a>: Enabled and Disabled</h4><p>There are some real world scenarios in which we have to disable features or do some hot fixes and disable corresponding tests for time being untill we get prior solution. We can do with the help of disable trait as shown below.</p><pre>@Suite(.enabled(if: true))<br>@Suite(.disabled(if: true))<br><br>@Test(.enabled(if: true))<br>@Test(.disabled(if: true))</pre><p>As shown above we can enable or disable collection of tests i.e. <strong>@Suite</strong> or individual <strong>@test </strong>i.e. alternate to<a href="https://developer.apple.com/documentation/xctest/xctskip"><strong>XCTSkip</strong></a> and<strong> </strong><a href="https://developer.apple.com/documentation/xctest/3521325-xctskipif"><strong>XCTSkipIf()</strong></a>.</p><h4><a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/withknownissue(_:isintermittent:sourcelocation:_:)-95r6o">Known Issue</a></h4><p>Some time we are aware of the known issue but we still want to proceed. On such scenarios we can use <strong>withKnownIssue(“Message”) </strong>to deal same.</p><pre>withKnownIssue(&quot;Grill is out of fuel&quot;) {<br>   // proceed<br>}</pre><h4>Ohhkkay!!!</h4><p>Hope you get an overview of new testing framework and expecting to walk through the attached links to dig deep. The framework is more concise and easy to migrate. I’m sure your previous test code will be reduced after this.</p><h4>Next…</h4><p><strong>Note:</strong> With <strong>Xcode 16</strong> and <strong>Swift 6</strong> you might get some errors related to concurrency specifically <strong>non-isolated</strong> or <strong>Sendable</strong> changes. <br>Please visit to below articles for details:</p><ol><li><a href="https://www.avanderlee.com/concurrency/concurrency-safe-global-variables-to-prevent-data-races/"><strong>Concurrency-safe global variables to prevent data races</strong></a></li><li><a href="https://www.avanderlee.com/swift/sendable-protocol-closures/"><strong>Sendable and @Sendable closures explained with code examples</strong></a></li></ol><h4><strong>Links:</strong></h4><ol><li><a href="https://swiftpackageindex.com/apple/swift-testing/main/documentation/testing/migratingfromxctest"><strong>Migration from XCTest</strong></a></li><li><a href="https://github.com/apple/swift-testing."><strong>Swift Testing Github</strong></a></li><li><a href="https://developer.apple.com/videos/play/wwdc2024/10179/"><strong>WWDC24: Swift Testing</strong></a></li></ol><h4>I hope you get overview of new test framework !!!</h4><h3>Happy Coding 😎 !!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=102c8d309185" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Combine: Quick Usage]]></title>
            <link>https://medium.com/@abhishekthapliyal/ios-combine-quick-usage-7ac06a58e4f0?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ac06a58e4f0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[combine-framework]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 02:22:23 GMT</pubDate>
            <atom:updated>2024-07-24T04:28:37.027Z</atom:updated>
            <content:encoded><![CDATA[<p>With the rapid development of SwiftUI Applications <strong>Combine</strong> plays major role to full fill reactive programming. In this blog we are going to discuss some operators and Subjects that we use most of the time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UGYmU-BizGOzoJGNFjGllg.png" /></figure><h4>1. Assign, Sink and Cancellable</h4><p><strong>Assign</strong> is used for assigning a value of publisher to another variable inside same class via keypath.</p><p><strong>Sink</strong> is used to observe the value of publisher coming from upstream.</p><p>Both the operator returns cancellable value of type <strong>AnyCancellable</strong> which is disposed when class deintialized in order to avoid memory leaks.</p><pre>import Combine<br><br>final class SinkAssignDemo {<br>    @Published var pubOne: Int? = 0<br>    @Published var pubTwo: Int = 0<br><br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        $pubOne<br>            .compactMap { $0 }<br>            .assign(to: \.pubTwo, on: self)  // assign<br>            .store(in: &amp;cancellables)<br>        <br>        $pubTwo<br>            .sink { [weak self] value in    // sink<br>                print(&quot;Output: &quot;, value)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>let demo = SinkAssignDemo()<br>(0..&lt;5).forEach {<br>    demo.pubOne = $0<br>}</pre><p>Here is the expected output</p><pre>Output:  0  // Initial Value<br>Output:  0  // Value from loop starting from 0<br>Output:  1 <br>Output:  2 <br>Output:  3 <br>Output:  4 </pre><h4>2. Combine Latest</h4><p>Combine latest is used when we have to combine publishers in such a way that when any of them gets updated, on receiver we get latest value of both. Here you can combine publisher of different data type.</p><pre>import Combine<br><br>final class CombineLatestDemo {<br>    @Published var pubOne: Int = 0<br>    @Published var pubTwo: String = &quot;_&quot;<br><br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    init() {<br>        Publishers<br>          .CombineLatest($pubOne, $pubTwo)<br>          .sink { (value1, value2) in<br>             print(&quot;Output:&quot;, value1, value2)<br>          }<br>          .store(in: &amp;cancellables)<br>    }<br>}<br><br><br>let demo = CombineLatestDemo()    // 1. Output: 0 _<br>demo.pubTwo = &quot;1&quot;                 // 2. Output: 0 1<br>demo.pubTwo = &quot;2&quot;                 // 3. Output: 0 2<br>demo.pubOne = 1                   // 4. Output: 1 2</pre><p>In above example we took two publishers and assigned default values. On class initializer they will emit default values and afterwards the latest assigned values i.e. <strong>0 _</strong>.</p><p><strong>Output 2</strong> : Shows <strong>0 1</strong> as <strong>pubTwo</strong> latest value is now <strong>“1”</strong> and same for <strong>Output 3</strong></p><p><strong>Output 4</strong> : Shows <strong>1 2</strong> as now <strong>pubOne</strong> latest value is <strong>1</strong></p><h4>3. Merge</h4><p>Merge is used when we have to merge publishers in such a way that when any of them gets updated, on receiver we get updated value either of them. Here you can merge publisher of same data type only.</p><pre>import Combine<br><br>final class MergeDemo {<br>    @Published var pubOne: Bool = false<br>    @Published var pubTwo: Bool = true<br><br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br><br>    init() {<br>        Publishers<br>          .Merge($pubOne, $pubTwo)<br>          .sink { value in<br>              print(&quot;Output:&quot;, value)<br>          }<br>          .store(in: &amp;cancellables)<br>    }<br>}<br><br><br>let demo = MergeDemo()    // 1. Output: false<br>                          // 2. Output: true<br><br>demo.pubTwo = true        // 3. Output: true<br>demo.pubOne = false       // 4. Output: false<br>demo.pubTwo = false       // 5. Output: false<br>demo.pubOne = true        // 6. Output: true</pre><p>In above example we took two publishers and assigned default values. On class initializer they will emit default values and afterwards whatever the latest values assigned with be emitted.</p><p><strong>Output 1, 2</strong> : <strong>pubOne</strong> default’s value is <strong>false</strong> but <strong>pubTwo</strong> is <strong>true</strong> so as an <strong>Merge</strong> order the latest value will be of <strong>pubTwo</strong> i.e. <strong>true</strong></p><p><strong>Output 3</strong> : <strong>pubTwo</strong> assigned <strong>true</strong> then the output will be <strong>true</strong></p><p><strong>Output 4</strong> : <strong>pubOne</strong> assigned <strong>false</strong> then the output will be <strong>false</strong> and so on.</p><h4>4. Filter and Compact Map</h4><p>Filter is used to filter out elements in stream. It’s closure requires a <strong>boolean</strong> condition in order to meet expectations similar to like we have in array.</p><p>Compact map is used to avoid <strong>nil</strong> values in stream like we have in array.</p><pre>import Combine<br><br>final class FilterCompactMapDemo {<br>    @Published var publisher: Int?<br>    <br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        $publisher<br>            .compactMap { $0 }        // Operator 1<br>            .filter { $0 % 2 == 0 }   // Operator 2<br>            .sink { value in<br>                print(&quot;Output:&quot;, value)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>let demo = FilterCompactMapDemo()<br>(0..&lt;10).forEach {<br>    demo.publisher = $0<br>}</pre><p>In above code if we remove <strong>Operator 1</strong> then we have to modify <strong>filter</strong> as something below</p><pre>.filter { value in<br>    guard let value else { return false }<br>    return value % 2 == 0<br>}</pre><p>This will return optional output as show below</p><pre>Output: Optional(0)<br>Output: Optional(2)<br>Output: Optional(4)<br>Output: Optional(6)<br>Output: Optional(8)</pre><p>Including <strong>Operator 1 </strong>will have output as shown below</p><pre>Output: 0<br>Output: 2<br>Output: 4<br>Output: 6<br>Output: 8</pre><p>As mentioned <strong>compactMap</strong> will unwrap values hence we get output with non-optional values.</p><h4>5. Remove Duplicates</h4><p>Remove duplicate is used to remove duplicates elements coming from upstream. Remember the data type for which it will be used should be Equatable.</p><pre>import Combine<br><br>final class RemoveDuplicatesDemo {<br>    @Published var publisher: Int = 0<br>    <br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        $publisher<br>            .removeDuplicates()<br>            .sink { value in<br>                print(&quot;Output:&quot;, value)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>let demo = RemoveDuplicatesDemo()<br>(0..&lt;10).forEach { _ in<br>    demo.publisher = 1<br>}</pre><p>Here the output will be <strong>0</strong> and <strong>1</strong></p><h4>6. Drop First</h4><p>Drop first operator is used drop first <strong>n </strong>elements.</p><pre>import Combine<br><br>final class DropDemo {<br>    @Published var publisher: Int = 0<br>    <br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        $publisher<br>            .dropFirst(1) // OR dropFirst()<br>            .sink { value in<br>                print(&quot;Output:&quot;, value)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>let demo = DropDemo()<br>(1..&lt;3).forEach {<br>    demo.publisher = $0<br>}</pre><p>In above you pass any no. of count for which it will drop first <strong>n</strong> elements.</p><p><strong>Output: 1</strong><br><strong>Output: 2</strong></p><h4>7. First and Last</h4><p>First and Last are the publisher that will return first and last elements of stream and finish i.e. they will called once and will be finished. In case of <strong>last()</strong> it requires stream to finish so it will not work with <strong>Published</strong> properties.</p><pre>let array = [1, 2, 3, 4]<br>let cancellable = array.publisher<br>    .first()<br>    .sink { value in<br>        print(&quot;Output: &quot;, value)<br>    }</pre><p><strong>Output: 1</strong></p><p>Here we very first element of stream.</p><pre>let array = [1, 2, 3, 4]<br>let cancellable = array.publisher<br>    .last()<br>    .sink { value in<br>        print(&quot;Output: &quot;, value)<br>    }</pre><p><strong>Output: 4</strong></p><p>Here stream will finished so we can see the output.</p><p>Below example where we explicitly finish stream.</p><pre>let subject = PassthroughSubject&lt;Int, Never&gt;()<br>let cancellable = subject<br>    .last()<br>    .sink { value in<br>        print(&quot;Output: &quot;, value)<br>    }<br><br>(1..&lt;5).forEach {<br>    subject.send($0)<br>}<br><br>subject.send(completion: .finished)</pre><p><strong>Output: 4</strong></p><p><strong>subject.send(completion: .finished) </strong>will finish stream.</p><h4>8. Current Value Subject and Pass Through Subject</h4><p><strong>CurrentValueSubject</strong> and <strong>PassThroughSubject </strong>are the subjects that can act as publisher and subscriber. The main difference between both is <strong>CurrentValueSubject </strong>retains it’s latest value while the other not<strong>.</strong></p><p>Both subjects<strong> </strong>works similar to <strong>Published</strong> except that subjects doesn’t participate in updating UI. If we need to update UI then we need call <strong>self.objectWillChange.send()</strong> explicitly having said that class conforms to <strong>ObservableObject</strong> protocol.</p><pre>import Combine<br><br>final class FirstLastDemo {<br>    let passThroughSubject = PassthroughSubject&lt;Int, Never&gt;()<br>    let currentValueSubject = CurrentValueSubject&lt;Int, Never&gt;(-1)<br><br>    <br>    private var cancellables = Set&lt;AnyCancellable&gt;()<br>    <br>    init() {<br>        passThroughSubject<br>            .sink { value in<br>                print(&quot;Output 1:&quot;, value)<br>            }<br>            .store(in: &amp;cancellables)<br>        <br>        currentValueSubject<br>            .sink { [weak self] value in<br>                guard let self else { return }<br>                print(&quot;Output 2:&quot;, value, currentValueSubject.value)<br>            }<br>            .store(in: &amp;cancellables)<br>    }<br>}<br><br>let demo = FirstLastDemo()<br><br>(0..&lt;2).forEach {<br>    demo.currentValueSubject.send($0)<br>    demo.passThroughSubject.send($0)<br>}</pre><p>The output as expcted below. Catch is that with <strong>CurrentValueSubject </strong>you can access to current value and able to access latest value even inside <strong>sink unlike </strong><strong>Published </strong>variable, user will get the previous value on direct access inside <strong>sink.</strong></p><pre>Output 2: -1 -1<br>Output 2: 0 0<br>Output 1: 0<br>Output 2: 1 1<br>Output 1: 1</pre><p>The good part is instead of using closures we can pass subjects and observe in order to replace them to some extent.</p><h4>Misc: One Time Output Calls</h4><p>We can also create custom publisher that gives output whenever we call only via <strong>Deffered</strong> and <strong>Future </strong>.</p><p><strong>Deferred</strong> returns a new publisher until it have a subscription.<br><strong>Future </strong>is a publisher that produces a single value and then finishes or fails with promise that wraps operation in escaping closure in asynchronous fashion.</p><pre>enum APIError: Error {<br>    case `default`<br>    <br>    var message: String {<br>        &quot;Oops something went wrong!!!&quot;<br>    }<br>}<br><br>func request(value: Int) -&gt; AnyPublisher&lt;Int, APIError&gt; {<br>    Deferred {<br>        Future&lt;Int, APIError&gt; { promise in<br>            DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {<br>                let flag = Bool.random()<br>                promise(flag ? .success(value) : .failure(.default))<br>            }<br>        }<br>    }<br>    .eraseToAnyPublisher()<br>}</pre><p>In above example we create a custom publisher that works a kind of API call and returns output after certain time interval. Try it and see.</p><p>Hope you get some quick overview how things works in combine.</p><h3>Happy C😎ding !!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ac06a58e4f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with NodeJS and FCM with AWS Pinpoint Push Notifications]]></title>
            <link>https://medium.com/@abhishekthapliyal/tada-co-incidence-of-nodejs-and-fcm-59f6e9b1f682?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/59f6e9b1f682</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[react-native]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Thu, 31 Mar 2022 12:17:46 GMT</pubDate>
            <atom:updated>2023-11-15T12:42:45.353Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rlp_z4KgIkJknqgokIYSWA.png" /></figure><p>The agenda of this story is to realise that whatever you learned today or in past will be useful one day. You never know when situation strikes.<br>So here is what happen, I was working closely with my client and some how <a href="https://firebase.google.com/docs/cloud-messaging/http-server-ref"><strong>FCM Push Notifications</strong></a> are working fine at our end. But we were using <strong>FCM HTTP API</strong> to test. Our client was using AWS Pinpoint. Now since the clashes of SDKs and the server written in python.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FIfs66U0O00GBRL8tgh%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FIfs66U0O00GBRL8tgh%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FIfs66U0O00GBRL8tgh%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/d7da08a7560bc11fd1f3e1240b583026/href">https://medium.com/media/d7da08a7560bc11fd1f3e1240b583026/href</a></iframe><p>Since AWS provide almost every server language support and I have worked on Node JS almost 2 years back. So I decided to go back and create simple server. So I created a free AWS account and navigate to <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html">SDK for Node JS</a>.</p><p><strong>Note:</strong></p><ol><li>Don’t afraid of adding <strong>Credit Card Details</strong> while doing signup on <strong>AWS</strong>. As they will only charge if the usgage exceeds free plan.</li><li>To test push notifications from <strong>AWS Pinpoint</strong> console here is the <a href="https://docs.aws.amazon.com/pinpoint/latest/userguide/messages-mobile.html"><strong>document</strong></a>.</li></ol><p>For beginners seeking<strong> Node JS tutorial</strong>. I will recommend <a href="https://www.udemy.com/course/nodejs-express-mongodb-bootcamp/">this</a>.</p><p>I am expecting that you have basic knowledege of Node JS. Still you can setup project from here</p><ol><li><strong>VS Code:</strong> <a href="https://code.visualstudio.com/docs/nodejs/nodejs-tutorial">https://code.visualstudio.com/docs/nodejs/nodejs-tutorial</a></li><li><strong>MDN:</strong> <a href="https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment">https://developer.mozilla.org/en-US/docs/Learn/Server-side/Express_Nodejs/development_environment</a></li></ol><p>So situation is not that simple here as we go through Node JS SDK <a href="https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/getting-started-nodejs.html"><strong>Document</strong></a>.</p><pre>{<br>  &quot;name&quot;: &quot;aws-sdk-v3-iam-examples&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;dependencies&quot;: {<br>   &quot;@aws-sdk/client-s3&quot;: &quot;^3.32.0&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;<br>}</pre><p>Now according to this we are installing <strong>AWS S3 Client</strong>. But wait our requirement is to test notification using pinpoint. So we will add depedencies in <strong>package.json</strong> like below</p><pre>{<br>  &quot;name&quot;: &quot;FCM Test Server&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;main&quot;: &quot;index.js&quot;,<br>  &quot;author&quot;: &quot;Abhishek Thapliyal&quot;,<br>  &quot;dependencies&quot;: {<br>    &quot;@aws-sdk/client-pinpoint&quot;: &quot;^3.54.1&quot;,<br>    &quot;aws-sdk&quot;: &quot;^2.1094.0&quot;<br>  },<br>  &quot;type&quot;: &quot;module&quot;<br>}</pre><p>Hit the below command to install dependencies</p><pre>npm install</pre><p>Now as per <a href="https://docs.aws.amazon.com/pinpoint/latest/developerguide/send-messages-push.html"><strong>official document</strong></a>, Node JS Example for testing push notification will be updated as below. In doc you will see other targets as well like <strong>APNS</strong>, <strong>Baidu </strong>etc. But we need to use <strong>FCM</strong> so I have removed other services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTwoE_TK0Kg4hZHVeGJLBg.png" /></figure><p>Now you have to replace <strong>REGION</strong>, <strong>APPLICATION_ID</strong> and <strong>FCM</strong> <strong>TOKEN</strong>.</p><p><strong>REGION: </strong>You will get region on top right corner of AWS console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*ywhBVKfqedJ9swa7ExgIlQ.png" /></figure><p><strong>APPLICATION_ID: </strong>Search for pinpoint in AWS Console. Add a new project. It will ask for <strong>Configure features,</strong> select<strong> Push Notifications. </strong>It will ask for<strong> Push notifications services,</strong> choose <strong>FCM</strong> and add FCM Server key from FCM Console. You will get inside <strong>Project Settings &gt; Cloud Messsaging.</strong></p><p>You will get <strong>Application Id</strong> name as <strong>Project Id </strong>when project is created successfully in AWS Pinpoint dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1cfb85JSpPPCLb0QV3-Fgg.png" /></figure><p><strong>FCM</strong> <strong>TOKEN</strong> : You will get fcm token from device depending upon the mobile project you are working. Below are references for setup and get FCM Token</p><ol><li><strong>Android</strong>: <a href="https://firebase.google.com/docs/cloud-messaging/android/client">https://firebase.google.com/docs/cloud-messaging/android/client</a></li><li><strong>iOS</strong>: <a href="https://firebase.google.com/docs/cloud-messaging/ios/client">https://firebase.google.com/docs/cloud-messaging/ios/client</a></li><li><strong>React-Native</strong>: <a href="https://firebase.google.com/docs/cloud-messaging/ios/client">https://firebase.google.com/docs/cloud-messaging/ios/client</a></li></ol><p>Make sure you have requested notifications already before testing.</p><p>I have used <strong>RawContent </strong>as I wanted to support background notification as per FCM Payload Structure. You can play around with properties from <a href="https://docs.aws.amazon.com/pinpoint/latest/apireference/templates-template-name-push.html"><strong>here</strong></a>.</p><p>So In your request controller you have to call send notification method like this</p><pre>const { SendMessage } = require(&quot;./Location /to/pinpoint_notification_service.js&quot;);</pre><pre>.<br>..<br>...</pre><pre>SendMessage();</pre><p>Use <strong>async await</strong> to make flow as per your requirement.</p><p>Hit the API and See the magic 😮😮</p><p>All document links are attached. You can check and feel free to add feedback.</p><h4>Happy Coding 😄😄!!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59f6e9b1f682" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploy iOS Application to AppCenter via Github Actions (Manual Code SignIn)]]></title>
            <link>https://medium.com/@abhishekthapliyal/deploy-ios-application-to-appcenter-via-github-actions-manual-code-signin-98238a5d6284?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/98238a5d6284</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[fastlane]]></category>
            <category><![CDATA[cicd]]></category>
            <category><![CDATA[appcenter]]></category>
            <category><![CDATA[github-actions]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Mon, 28 Mar 2022 03:16:35 GMT</pubDate>
            <atom:updated>2022-03-29T04:13:05.721Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IV9f75shqXRpHXOHY6h46w.jpeg" /></figure><p>🌅 Good Morning Guys ☕️<br>⏰ 25th March 2022 08:15 hrs IST</p><p>I know you have read lots of tutorials same like this. But for me, this is my latest achievement from the last 4 days to learn CI/CD which I’m procrastinating on for a long time. Here is the simplest way to automate uploading iOS build to <strong>AppCenter</strong> with <strong>Fastlane</strong> and <strong>Github Actions</strong>.</p><p>Let&#39;s make a list we needed.</p><ol><li>Apple Account Mandatory for code signing. If you are in a team/organization, you ask for a testing bundle and certificates.</li><li>Xcode 13.3/13.2.1, well that is independent but I’m using both so just to mention for clarifying any confusion.</li><li>Github, AppCenter, Apple accounts.</li><li>Cocoapods, Fastlane lib. No worries I have added steps where ever required.</li></ol><p><strong>P.S.: We are pushing build with a development profile to AppCenter and NOT for AppStore because of limited access 😅.</strong></p><p>Let&#39;s start with some lazy steps.</p><h4>Account Setup</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ftenor.com%2Fembed%2F17173172&amp;display_name=Tenor&amp;url=https%3A%2F%2Ftenor.com%2Fview%2Fsign-up-register-log-in-be-with-us-gif-17173172&amp;image=https%3A%2F%2Fc.tenor.com%2FaRJe6lmQUqUAAAAd%2Fsign-up-register.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=tenor" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/95261a0002bf45d09b2016d27152a852/href">https://medium.com/media/95261a0002bf45d09b2016d27152a852/href</a></iframe><p><strong>Github:</strong> <a href="https://github.com/signup">https://github.com/signup</a><br><strong>AppCenter</strong>: <a href="https://appcenter.ms/create-account">https://appcenter.ms/create-account</a><br><strong>Apple Account</strong>: I feel that is already provided by your organization. But still here: <a href="https://support.apple.com/en-in/HT204316">https://support.apple.com/en-in/HT204316</a></p><p><strong>Xcode: </strong>Download Xcode from here <a href="https://developer.apple.com/xcode/">https://developer.apple.com/xcode/</a><br>Open Xcode, go to top menu <strong>Xcode &gt; Preferences. </strong>A dialogue will open, on the bottom left tap on the ‘<strong>+’</strong> button, Select Apple Id. Add your credentials and after that when you see your account tap on download profiles.</p><h4>AppCenter Setup</h4><p><a href="https://docs.microsoft.com/en-us/appcenter/dashboard/creating-and-managing-apps">Here</a> is the helping doc for the dashboard. Login to AppCenter and you will see a dashboard like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UdBjhlDc6lmLf4E3OR-ZUw.png" /></figure><p>Top right you will see <strong>Add new app</strong> button, A side menu will appear to ask below details<br>1. <strong>App Name:</strong> AppCenterDemo-iOS<br>2. <strong>Release Type:</strong> Beta<br>3. <strong>OS:</strong> iOS<br>4. <strong>Platform: </strong>Objective-C / Swift.</p><p>Tap on <strong>Add new app</strong> button on the bottom right and it will redirect you to the app’s dashboard page. There you will get app secret and cocoapods installation link as well. Save the app secret for the next section.</p><h4>Xcode Project Setup</h4><p>Open Xcode, create a new project any name let&#39;s say <strong>AppCenterDemo. </strong>You can learn from <a href="https://developer.apple.com/documentation/xcode/creating-an-xcode-project-for-an-app">here</a> as well just in case. Click on Project and you will general settings, tap on signing and capabilities, uncheck automatic sign in and</p><ol><li>Choose your organization&#39;s team in the dropdown.</li><li>Setup your bundle id like <strong>com.organization.appname.</strong></li><li>Update your <strong>.gitignore</strong> file before pushing your code to GitHub Like below. We are removing pods, DeriveData, Fastlane some files which are not required in the repo.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5BoYs-nH8kfF9iko3wBK6A.png" /></figure><p>4. Download the provisioning profile and keep a soft copy of the same as well for later usage in Fastlane.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bebACUkA8tbigd_l8bJycA.png" /></figure><p>5. Open Keychain, and check the Apple Development certificate provided by your organization or your developer account, tap on to see the dropdown.</p><p>6. You will see a private key. right-click on it and select the export option</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XhrVSzApwxZf2zh5lScfRA.png" /></figure><p>7. Save the <strong>.p12</strong> file for later use. Here I have created <strong>ios_dev_certificate.p12</strong>. Use the password when prompted for a password and save it for later use in this tutorial.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wHB99cvvgj9X86GYLvh8RA.png" /></figure><p>The hard part is done 😅</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0Iyl55kTeh71nTXy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0Iyl55kTeh71nTXy%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0Iyl55kTeh71nTXy%2Fgiphy.gif&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="290" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c34bed6895f7b2bdc9e6633c4417dad/href">https://medium.com/media/1c34bed6895f7b2bdc9e6633c4417dad/href</a></iframe><p>8. Setup cocoapods from <a href="https://guides.cocoapods.org/using/getting-started.html">here</a> if not done in past. Open podfile and add like below. Here we are integrating the <a href="https://docs.microsoft.com/en-us/appcenter/sdk/getting-started/ios"><strong>AppCenter</strong></a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*arRMe6x7CbbY4239D9c5sg.png" /></figure><p>Go to the terminal inside the root directory and run <strong>pod install</strong> in the terminal. You will observe a workspace is created like a project file. Open workspace project.</p><p>9. In the <strong>AppDelegate</strong> file or in the main file for <strong>SwiftUI projects</strong>, add the code below. Declare a constant variable for <strong>appSecret. AppSecret </strong>is the same I mentioned at the end of the previous section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jxt5JX9X4kIjAEQQDAuBpg.png" /></figure><p>10. Run/Build your project in order to check everything is working.</p><h4>Fastlane Setup Part 1</h4><p>For all further steps, I will recommend <a href="https://code.visualstudio.com/download"><strong>VS Code</strong></a><strong> </strong>Editor. As we will get the project structure and terminal in a single window and we can access <strong>.extension</strong> files as well.</p><p>Run sudo gem install fastlane for global installation. Open terminal, navigate to project root directory and run fastlane init<br><a href="https://docs.fastlane.tools/getting-started/ios/setup/">Doc</a> for iOS Setup.</p><p>You will see a Fastlane folder with Gemfile, AppFile, Fastfile and plugin files.<br>Now add <a href="https://github.com/microsoft/fastlane-plugin-appcenter">AppCenter Plugin</a> for Fastlane via command fastlane add_plugin appcenter.</p><p>Now initial Fastlane setup add these in <strong>Gemfile </strong>and run bundle install.<br><a href="https://docs.fastlane.tools/getting-started/ios/setup/">Here</a> is the<strong> Gemfile</strong> setup at the end of the doc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PCZ7e_UQr0poQPRvaeeZpA.png" /></figure><p>These are libraries will be used by Fastlane as an initial setup. <a href="https://rubygems.org/gems/dotenv-rails/versions/2.1.1">Dotenv-rails</a> is used to load the environment while running Fastlane.</p><p>To specify the ruby version, add <strong>.ruby-version </strong>file and inside that add a single line string 2.6.8. This will be used by Fastlane.</p><p>Now add .env file and these properties</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TYdtUHvGqooPGlVomAmp7Q.png" /></figure><p>These are environment variables used in shell script and Fastfile later in the tutorial.</p><p>General Settings values you can get from iOS Project Directory. Workspace and Project path are basically ios workspace and project file path. The scheme is iOS project scheme that is used to build the app.</p><p><strong>BUILD_CONFIGURATION=Debug<br>SCHEME=AppCenterDemo<br>EXPORT_METHOD=development</strong></p><p>Check the<strong> </strong><a href="https://docs.fastlane.tools/actions/gym/"><strong>Parameters</strong></a> section for more details of the export method, scheme, workspace, Project Path and build configuration.</p><p>To get the <strong>APP_CENTER_APP_NAME</strong> and <strong>APP_CENTER_OWNER_NAME</strong> here is the <a href="https://github.com/microsoft/fastlane-plugin-appcenter#a-note-on-app-name">link</a>:</p><blockquote><a href="https://appcenter.ms/users/%7Bowner_name%7D/apps/%7Bapp_name">https://appcenter.ms/users/{owner_name}/apps/{app_name</a>}</blockquote><p><strong>APP_CENTER_API_KEY:</strong> This is the same used previously in <strong>AppDelegate</strong>. Update here as well.<br><strong>APP_CENTER_API_TOKEN:</strong> <a href="https://appcenter.ms/settings/apitokens">https://appcenter.ms/settings/apitokens</a><br>Use this link to get API Token.</p><h4>Github Repo</h4><p>You need to create a new repository in order to proceed further.<br>Beginner, please follow these docs for the Github repository setup.</p><ol><li><a href="https://docs.github.com/en/get-started/quickstart/create-a-repo">Create Repository</a></li><li><a href="https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository">Cloning</a></li><li><a href="https://docs.github.com/en/authentication/connecting-to-github-with-ssh">SSH Setup</a></li></ol><p>Now add a new folder name <strong>provision </strong>inside <strong>fastlane</strong> folder and move the earlier <strong>Dev_Profile.mobileprovision </strong>file inside. Now push the code to the repo.</p><h4>Github Secrets</h4><p>Now we have to setup Github Secrets in order to secure the <strong>.p12</strong> file and <strong>credentials</strong>. Follow this <a href="https://docs.github.com/en/actions/security-guides/encrypted-secrets">doc</a> for encrypted secrets and create as follow</p><p>Github Deploying Xcode Applications <a href="https://docs.github.com/en/actions/deployment/deploying-xcode-applications/installing-an-apple-certificate-on-macos-runners-for-xcode-development#creating-secrets-for-your-certificate-and-provisioning-profile">Doc</a></p><ol><li>Go to the directory where <strong>ios_dev_certificate.p12 </strong>is saved earlier. <br>Open terminal in the same directory and <br>runbase64 -i ios_dev_certificate.p12 | pbcopy. This will copy the base64 string in the pasteboard. You can check it via <strong>command+v</strong>. Save it in Github Secrets with the key name <strong>IOS_DEVELOPMENT</strong>.</li><li>The password we have saved while creating the above certificate will be saved in Github Secrets with the key name <strong>P12_PASSWORD</strong>.</li><li>Add one more value <strong>KEYCHAIN_PASSWORD </strong>for the keychain that will be used in Fastlane. I recommend make it strong.</li></ol><h4>Github Actions</h4><p>Now in the root directory of the project.</p><ol><li>Add nested folder <strong>.github/workflows.</strong></li><li>Add <strong>yml</strong> file name <strong>gh_actions.yml</strong> inside the <strong>workflows</strong> folder. There is no specific name you can choose any name.</li><li>Update your above <strong>yml </strong>file like below.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NPHnreFwF1UADpeBL-os_A.png" /></figure><p><strong>name:</strong> Workflow name.<br><strong>on:</strong> on which <a href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions#events">event</a> it will be triggered. Here I have added push i.e. on every push a build will be triggered.<br><strong>jobs: </strong>Series of actions that will be executed.<br><strong>build: </strong>Action Name.<br><strong>runs-on: OS Name </strong>in which actions will be executed.<br><strong>uses: actions/checkout@v2: </strong>Use to checkout branch<br><strong>uses: ruby/setup-ruby@v1: </strong>Ruby setup with <strong>bundler-cache: true </strong>so that Gemfile libraries can be used.<br><strong>name:</strong> Specifying name.<br><strong>run:</strong> to run shell script command<br><strong>env: </strong>Here we will mention environment variables that will be used in Fastlane and Github actions from Github Secrets.</p><p><a href="https://docs.github.com/en/actions">Here</a> is the reference doc for actions. More details for the workflow file are <a href="https://docs.github.com/en/actions/learn-github-actions/understanding-github-actions#understanding-the-workflow-file">here</a>.</p><p><strong>Well, It’s afternoon 13:30 hrs IST. Have lunch and come back 😅</strong></p><h4>Fastlane Setup Part 2</h4><p>Here is the most important section that will actually deploy our app.</p><p>Below are the <strong>documented </strong><a href="https://docs.fastlane.tools/actions/"><strong>fastlane actions</strong></a><strong>. </strong>Please go through once before using.</p><p>Now open fastfile inside fastlane folder. Update the code like below.<br>from this <a href="https://dev.to/matt_catalfamo/how-to-build-and-manually-sign-an-ios-app-with-fastlane-2256">blog</a> I have taken reference to certificates setup. Our agenda is divided in three setps.</p><ol><li>Add action to generate <strong>KeyChain</strong> for code signIn.</li><li>Add action to generate <strong>iOS Build</strong>.</li><li>Add action to upload build to <strong>AppCenter</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H-08wYvm8smQHqUyLBBBPg.png" /></figure><ol><li>create_keychain : use to create keychain in github runner environment. <a href="https://docs.fastlane.tools/actions/create_keychain/"><strong>Doc</strong></a></li><li>install_provisioning_profile : use to install provision profiles for code sign in. <a href="http://docs.fastlane.tools/actions/install_provisioning_profile/#install_provisioning_profile"><strong>Doc</strong></a></li><li>import_certificate : use to import <strong>.p12</strong> certificate from github secrets mentioned in env file inside<strong> github actions yml</strong> file previously. <a href="http://docs.fastlane.tools/actions/import_certificate/#import_certificate"><strong>Doc</strong></a></li><li>setup_ios_profiles : It’s the custom Fastlane action created by me. <a href="http://docs.fastlane.tools/create-action/#local-actions"><strong>Doc</strong></a><strong> </strong><a href="https://spin.atomicobject.com/2021/05/21/custom-bash-script-fastlane/"><strong>Example</strong></a></li><li>Open terminal and run bundle exec fastlane new_action. It will ask you name for action. I have added <strong>setup_ios_profiles</strong>. A <strong>setup_ios_profiles.rb </strong>will be generated inside fastlane folder. Add below code.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Rfu7eRmfhzxgsLcqg57lw.png" /></figure><p>Now create new file <strong>setup_code_signin.sh</strong>, open terminal in same directory and run chmod u+x ./setup_code_signin.sh. This command will make file executable for user. After that update code below</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QOZ4SJlL0-oHKdOjWOHrzg.png" /></figure><p>This script will convert saved base64 string from github secrets, mentioned in yml file, to <strong>.p12</strong> file.</p><p>6. xcversion: use to specify Xcode version.</p><p>7. clear_derived_data: use to clear derive data use to clear derive data</p><p>8. xcclean : use to clean project with specified scheme.</p><p>9. cocoapods : use to install cocoapods with repo update if specified.</p><p>Now code signIn and fastlane project in github action is almost setup. We have to configure rest two setps. As shown above fastfile code build_ios_app will generate build for iOS <strong>(</strong><a href="http://docs.fastlane.tools/actions/build_ios_app/#build_ios_app"><strong>Reference Doc</strong></a><strong>)</strong>. It will take values mentioned in <strong>.env</strong> file. Have a closer to export method, you can change to as per <a href="http://docs.fastlane.tools/actions/build_ios_app/#parameters"><strong>doc</strong></a></p><blockquote>export_method :Method used to export the archive. Valid values are: app-store, validation, ad-hoc, package, enterprise, development, developer-id and mac-application.</blockquote><p>And the last part upload to <a href="https://github.com/microsoft/fastlane-plugin-appcenter#usage"><strong>AppCenter</strong></a> i.e. appcenter_upload : This method will take <strong>App. Name</strong>, <strong>API Token</strong> and <strong>Owner Name</strong> from <strong>.env</strong> file. We have discussed earlier as well. As per doc</p><pre><strong>owner_type</strong>: &quot;user&quot;, # Default is user - set to organization for appcenter organizations<strong><br>app_name</strong>: &quot;&lt;appcenter app name (as seen in app URL)&gt;&quot;, <br><strong>notify_testers</strong>: true # Set to false if you don&#39;t want to notify testers of your new release (default: `false`)</pre><p>Now push your code and see the magic. If all goes well then in a sample logs for successful app upload to <strong>AppCenter </strong>will looks like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tSeRiZuAbeMYBmNVK3VOTg.png" /></figure><p>You can <strong>cmd+click</strong> the link to navigate app center release page as well.</p><p>I hope you will get an idea <strong>CI/CD</strong> works. You can explore more yourself for TestFlight builds as well as managing several environments.</p><h3>HAPPY CODING 😃😃<br>Good Night 😴 🛌</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98238a5d6284" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Swift Custom TabBarController with Tab Item Animation]]></title>
            <link>https://medium.com/nickelfox/ios-swift-custom-tabbarcontroller-with-tab-item-animation-b26f6a6e2c62?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/b26f6a6e2c62</guid>
            <category><![CDATA[uitabbarcontroller]]></category>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Thu, 30 Jul 2020 19:53:21 GMT</pubDate>
            <atom:updated>2022-12-19T13:26:28.330Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*WUx3GvXaTl9_fTeC.gif" /></figure><p>Looks cool right!!!<br>But a normal iOS Developer would prefer to go with the library. But just like in my previous stories, I would like to introduce how we can build <strong>TabBarController with Tab Item Animation</strong>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FoOPMSxI6AlEB5nYW2j%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FoOPMSxI6AlEB5nYW2j%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FoOPMSxI6AlEB5nYW2j%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3e19afba60d6c8cb86dffa9281957f2/href">https://medium.com/media/c3e19afba60d6c8cb86dffa9281957f2/href</a></iframe><p>Hang on 😃😃😃!!!</p><p>Okay so create a new Xcode project. Navigate to <strong>Main.Storyboard</strong></p><ol><li>Add <strong>UIView</strong> with the height relative to superView i.e add equal height constraint and set the multiplier to 0.12. Enable Safe are layout guide in the size inspector category in the right-hand side.</li><li>Add horizontal <strong>UIStackView</strong> inside above view. Add left &amp; right constraints to 15 &amp; 15 respectively. Add 0 constraint value from top &amp; bottom to safe area.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tefKe-yK4ysLM32lr_nkwg.png" /><figcaption>Stack View after adding constraint.</figcaption></figure><p>3. Create <strong>IBOulet</strong> of stack view inside default ViewController class. Leave it for a while we’ll be back soon.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FTNOq5o37nNXX2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FTNOq5o37nNXX2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FTNOq5o37nNXX2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="185" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfae1d8a252f37fbc90878a344ded704/href">https://medium.com/media/dfae1d8a252f37fbc90878a344ded704/href</a></iframe><p>Definitely😃😃😃!!!</p><h4>StackViewItem: The UI</h4><p>This is the most important that we need to focus on. As all the animation is dependent on this class.</p><ol><li>Quickly add a new file with name <strong>BottomStackItem </strong>as shown below.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc9c4d929d20b708877dcd7db4e3e1f3/href">https://medium.com/media/fc9c4d929d20b708877dcd7db4e3e1f3/href</a></iframe><p>This class object is associated with each item in the bottom stack view item.<br>variable title and image are the data and <strong>isSelected</strong> flag is maintained in order to handle selection/de-selection of item.</p><p>2. Now add a new <strong>UIView</strong> XIB file with name <strong>StackItemView</strong> for bottom stack item.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oEo4PMy_H2o5j-RHAlgWYg.png" /></figure><p>3. Add <strong>UIView</strong> inside above with 10,0,10 and 0 constraints respectively from the top going anti-clockwise.</p><p>4. Add <strong>UIImageView</strong> and <strong>UILabel</strong> with vertical centre-aligned within superview. Spaces between image and label are 15, 5 &amp; 10 from left to right respectively. Choose a font you like, I prefer <strong>Avenir Next</strong>.</p><h4>StackViewItem: The Subclass</h4><p>Add a subclass of above stack Item name <strong>StackItemView</strong> i.e.<strong> </strong>with the same name as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7692d26ce283647c23c11d43c7b8c99/href">https://medium.com/media/a7692d26ce283647c23c11d43c7b8c99/href</a></iframe><h4>Let me explain you step by step.</h4><ol><li><strong>StackItemViewDelegate: </strong>The Bottom stackview item’s tap action is routed to ViewController class via this protocol in order to change the state of selected item and de-select previously selected item.</li><li><strong>StackItemView: </strong>As already told the subclass of above Item UI. Update it’s setting in storyboard inside attribute inspector.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/522/1*qHUwEWCRTKGczBd4MztiUA.png" /><figcaption>StackView Settings</figcaption></figure><p>3.<strong> IBoutlet:</strong> as by name title and imgView are the outlets of the above item. The view inside the above item is <strong>highlightView.</strong> Its colour will be toggle on the selection/de-selection of item.</p><p>4. <strong>newInstance: </strong>View initializer. I prefer to write initializer within the class to avoid code redundancy. I have seen most of the new bee used to initialize the code everywhere. This could be the good learning for them.</p><p>5. <strong>delegate: </strong>As mentioned earlier for tap action routing. Hence we declared delegation variable. For more details visit here</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Protocols.html">https://docs.swift.org/swift-book/LanguageGuide/Protocols.html</a></p><p>6. <strong>addTapGesture: </strong>Adding gesture in the item. In order to make bottom stack item user interactive. Alternatively, you can add a button to cover the whole view with empty text, to get the same behaviour. The handler will call the function defined in the above protocol in order to tell ViewController to update tap action.</p><p>7. <strong>item: Any?: </strong>This is the data item for a particular stack item. On setting value to it, it will call configure method which will set data and <strong>isSelected</strong> state of stack item. it will be of type <strong>BottomStackItem</strong> class introduced initially.</p><p>8. <strong>isSelected: </strong>A computed property is added in order to update UI. Whenever user tap on particular stack item. Inside there a property observer is added to update UI, for more details visit this link.</p><p><a href="https://docs.swift.org/swift-book/LanguageGuide/Properties.html">https://docs.swift.org/swift-book/LanguageGuide/Properties.html</a></p><p>9. <strong>updateUI: </strong>This method called inside property observer mentioned on #7. It will first set the item’s <strong>isSelected.</strong></p><p>Now on the basis of param value <strong>isSelected </strong>in the function parameter, it will choose animation type and update UI. <strong>titleLabel’s</strong> text will be reset to empty in order to get default icon state and text is hidden and reverse will show text with a highlighted background.</p><p><strong>layoutIfNeeded </strong>is called in order to update stack view items while performing animation in order to maintain UI consistency in runtime.</p><p>All set to bottom stack. Let’s go back to our view controller to set data in order to see the awesome animation.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FKi9zObRfQlVja%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FKi9zObRfQlVja%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FKi9zObRfQlVja%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="174" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f0bb45245cca7c8bfe48fd9edf72ed4/href">https://medium.com/media/1f0bb45245cca7c8bfe48fd9edf72ed4/href</a></iframe><h4>Now you have to update your view code as shown below.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/155f16ed7d6a73359a7b21ae14095476/href">https://medium.com/media/155f16ed7d6a73359a7b21ae14095476/href</a></iframe><h4>Let’s go through step by step.</h4><ol><li><strong>currentIndex: </strong>Tracks the currently selected index. This is need to set the latest one and reset the previous one in the stack items.</li><li><strong>tabModels: </strong>Array of stack item’s data models.</li><li><strong>tabs:</strong> These are items based on <strong>tabModels. </strong>Property is <strong>lazy</strong> <strong>var</strong> as I need to access stored property inside and initialize tabs. It’s slightly different from the computed property. For more details refer <a href="https://docs.swift.org/swift-book/LanguageGuide/Properties.html">here</a>.</li><li><strong>setupTabs: </strong>In this, the tabs/bottom stack items will be assigned respective model on the sequentially from left to right in UI. The first bottom stack item will be selected initially just like normal <strong>UITabBar</strong> behaviour. for loop with <strong>enumerated</strong> is used to get index and value simultaneously.</li><li><strong>addArrangedSubview: </strong>This is the method used to add subview in <strong>UIStackView </strong>programmatically<strong>.</strong></li></ol><h3>RUN THE APP T😃 SEE THE AWES😃ME ANIMATI😃N</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NXKCph0uQACOeEUk1lFTTQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tJJjCdalPnZtgZJ1fdQsoA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rVUw-KWE1UFLMWSf496kIg.png" /></figure><p><strong>P.S:</strong> This is notch Screenshots. Bottom <strong>UIView</strong> Height may distort. So You need to manage height on the basis of notches and non-notches screens i.e play with the multiplier that we have set in Storyboard initially. Also, I haven’t made for landscape screen. So if someone is proficient in Autolayouts and size classes, can play around with it.</p><p><strong>For the tab bar controller, you have to use ContainerView with that will add/remove child views on tab bar item selection.</strong></p><h4>I hope you like this story. Feel free to reach out.😃😃😃</h4><p>I have attached the complete project here.</p><p><a href="https://github.com/Abhishek9634/MYTabBarDemo/tree/viaStack">Abhishek9634/MYTabBarDemo</a></p><h3>Cheers😃😃😃!!!</h3><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b26f6a6e2c62" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nickelfox/ios-swift-custom-tabbarcontroller-with-tab-item-animation-b26f6a6e2c62">iOS Swift Custom TabBarController with Tab Item Animation</a> was originally published in <a href="https://medium.com/nickelfox">Nickelfox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Swift Expandable TextView with Placeholder]]></title>
            <link>https://medium.com/nickelfox/ios-swift-expandable-textview-with-placeholder-fca5ed2556f4?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/fca5ed2556f4</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[uitextview]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Sat, 25 Jul 2020 06:43:26 GMT</pubDate>
            <atom:updated>2020-07-25T06:43:26.881Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Swift Expandable UITextView with Placeholder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JcwZqOeXY3O-zw98.jpg" /></figure><p>The reason why I’m putting this post because I don’t rely on libraries. In my opinion, if you want to be a good developer, you should explore the things to get to know inside the story. So moving on to the topic, I’ll cover</p><ol><li>Expandable Text View</li><li>Placeholder</li></ol><h4>Expandable Text View</h4><p>Setup a new Xcode project with suitable name you like. I named <strong>ExpandableTextViewDemo</strong>. Open Main.storyboard. A default view controller is provided with default class name <strong>ViewController</strong>. Steps to perform in Interface Builder IB.</p><ol><li>Now add <strong>UIView</strong> with height constraint value 50 at the bottom with a background with smoke white colour.</li><li>Inside that view add <strong>UIView</strong> again with constraint in sequence Top, Left, Bottom with values 8,15,8. Leave Right one for a while.</li><li>Add <strong>UIView’s</strong> (in Step 2) default border, corner radius 8 with background colour white.</li><li>Now add a button name send button with height and width 34, Right constraint 15 and bottom constraint 8, in <strong>UIView</strong> (in Step 1) at the right side.</li><li>Add button’s default border and corner radius to make it circular and add default icon as per your convenience.</li><li>Now add horizontal space OR Left constraint of button w.r.t to <strong>UIView</strong> (in Step 2).</li><li>Add <strong>UITextview</strong> inside <strong>UIView</strong> (in Step 2), with constraint 0,5,0,5 respectively. I have used default font size 14 for it.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PxPKxfEbIO1itJS-kqgv6Q.png" /></figure><p>Now go to <strong>ViewController </strong>class and add IBOutlets for</p><ol><li><strong>UIView’s</strong> (in Step 1) height constraint and it’s a bottom constraint.</li><li><strong>UITextView</strong></li></ol><p>Add <strong>IBAction</strong> for send button and add two variables</p><pre>private let maxHeight: CGFloat = 100    <br>private let minHeight: CGFloat = 50</pre><p>These variables are lower and upper bound for expandable text view height.</p><p>For managing height on the basis of text for the expandable view, we will use <strong>textview’s</strong> property <strong>contentSize.height</strong>. So an expandable view’s height can be expanded up to <strong>maxHeight</strong> and can’t squeeze or go beyond <strong>minHeight</strong>.</p><p>Now you have to observe keyboard notifications in order to handle slide animation as shown below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bfade441f81171ce243b6c6812674562/href">https://medium.com/media/bfade441f81171ce243b6c6812674562/href</a></iframe><p>I am using swift 5 so keyboard notifications name is changed, If you are in the older version then use below.</p><pre>NSNotification.Name.UIKeyboardWillShow<br>NSNotification.Name.UIKeyboardWillHide</pre><p>So as shown above on key will show notification handler, we are assigning bottom constraint to keyboard’s <strong>frame.size.height </strong>in<strong> </strong>order to get smooth slide up to input frame. To reset the bottom constraint position, we are using keyboard hide notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/401/1*ROW3fDm2TxG4QmODPBp6wA.png" /></figure><p>Ignore the placeholder that I’ll explain in a later section 😅😅😅.</p><p><strong>NOTE</strong>: If your view goes beyond keyboard frame probably your bottom constraint’s <strong>First Item</strong> and <strong>Second Item</strong> are interchanged. You can reverse it via a tap on any item and select reverse first and second item. finally, it should look like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u-o6etbjSLWmm7UsQek6cQ.png" /></figure><p>Now comes the main part handling the dynamic height of the view. You need to set <strong>UITextViewDelegate</strong> to <strong>ViewController</strong> following by conforming it with a delegate method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d543f43019182cbeac8fa3a9cee6c4/href">https://medium.com/media/48d543f43019182cbeac8fa3a9cee6c4/href</a></iframe><p>So In <strong>textViewDidChange</strong> delegate method, we are checking <strong>contentSize.height</strong>. If it goes beyond that <strong>maxHeight</strong> we are fixing <strong>commentConstraint’s</strong> value to 100.<br>If it goes beyond that <strong>minHeight</strong> we are fixing <strong>commentConstraint’s </strong>value<strong> </strong>to 50. else it will be equals to <strong>contentSize.height</strong> in order to get the dynamic expansion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*9vRym-nZUerG4PlGsOLG2Q.png" /></figure><p>and here you go 😃😃😃.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FB2MTuzDezeEqBKm76A%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FB2MTuzDezeEqBKm76A%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FB2MTuzDezeEqBKm76A%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb60ab85b0de443227bfc0b7b20c4218/href">https://medium.com/media/bb60ab85b0de443227bfc0b7b20c4218/href</a></iframe><p><strong>Placeholder!!! yeah coming </strong>😅😅😅<strong>.</strong></p><h4>Placeholder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GEFz4rNCI1fIiyRk6gGokA.png" /></figure><p>So the major problem occurs with <strong>UITextView</strong> is it doesn’t provide placeholder view by default, unlike <strong>UITextField</strong>. So go back to IB and add a <strong>UILabel</strong> just beyond <strong>UITextView </strong>and add constraints w.r.t to <strong>UITextView </strong>as -4 0,0,0.</p><p>Add text as per your convenience and in last add <strong>placeholderLabel</strong> as an outlet in the above class. Add <strong>UITextView’s</strong> <strong>Delegate</strong> method as shown below</p><pre>func textViewDidEndEditing(_ textView: UITextView) {            self.placeHolderLabel.isHidden = !textView.text.isEmpty    <br>}</pre><p>and in last add below code to the above <strong>textViewDidChange</strong> method after if-else condition.</p><pre>self.placeHolderLabel.isHidden = !textView.text.isEmpty</pre><p>So the logic behind is that placeHolder Label will toggle its visibility on the basis of the empty text. Re-run the project and you will see the magic. A Complete <strong>ViewController</strong> code I have attached here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f71fea0849d3a4bab603906818127d2/href">https://medium.com/media/7f71fea0849d3a4bab603906818127d2/href</a></iframe><p>I’m expecting readers to try out other simple stuff that doesn’t require to add pods or library in your project. There are two benefits of doing this</p><ol><li>Project Size will decrease hence faster build.</li><li>Skills improvement.</li></ol><p>Hope you all got my point😅😅😅.</p><p>Cheers😃😃😃!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fca5ed2556f4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nickelfox/ios-swift-expandable-textview-with-placeholder-fca5ed2556f4">iOS Swift Expandable TextView with Placeholder</a> was originally published in <a href="https://medium.com/nickelfox">Nickelfox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Swift UICollectionView With Horizontal Pagination]]></title>
            <link>https://medium.com/swlh/ios-swift-uicollectionview-with-horizontal-pagination-13ba1e4d21ef?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/13ba1e4d21ef</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[pagination]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Fri, 24 Jul 2020 05:05:09 GMT</pubDate>
            <atom:updated>2020-09-15T19:39:58.329Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*6QxXnvt9sht5k3Im" /></figure><p>Hey, today I’m presenting you horizontal pagination in swift 5. The reference I have taken from one of my organisation’s library.</p><p><a href="https://github.com/Nickelfox/PaginationUIManager">Nickelfox/PaginationUIManager</a></p><p>If you are new bee then please refer to following links first</p><ol><li><a href="https://developer.apple.com/documentation/uikit/uicollectionview">https://developer.apple.com/documentation/uikit/uicollectionview</a></li><li><a href="https://www.raywenderlich.com/9334-uicollectionview-tutorial-getting-started">https://www.raywenderlich.com/9334-uicollectionview-tutorial-getting-started</a></li></ol><h4>Horizontal Pagination</h4><p>Basic pagination works as you pulled to a threshold value. Beyond that, it will hit API and gives some array items back, that you will append to the main array. Pagination consist of 2 things <strong>refresh all</strong> and <strong>load more</strong>. Refresh all works when you need fresh content from the beginning and load more works when you need more data at the end. In context with horizontal pagination you will drag collection towards the right to refresh all and in case of load more, you will scroll to last content and drag towards left.</p><p>So moving ahead and let’s create a new project name <strong>HorizontalPaginationDemo.</strong></p><h4>Project Setup</h4><ol><li>Open default <strong>Main.Storyboard,</strong> there is default view controller in Interface Builder (IB), add <strong>UICollectionView </strong>with top, left, right and height to 0,0,0 and 200 respectively.</li><li>There is a default <strong>UICollectionViewCell</strong> present in the collection view. Extend it and add <strong>UILabel</strong> in the centre.</li><li>Create an <strong>IBOutlet</strong> of collection view in default <strong>ViewController</strong> Class and delegates methods for no. of rows and cell for row.</li></ol><pre>func setupCollectionView() {<br>    self.collectionView.delegate = self<br>    self.collectionView.dataSource = self<br>}</pre><ol><li>For horizontal or vertical pagination we need to specify in which direction collection view will scroll strictly. So for that set collection view property <strong>alwaysBounceHorizontal</strong> to <strong>true</strong>.</li></ol><pre>self.collectionView.alwaysBounceHorizontal = true</pre><p>5. Add a subclass of <strong>UICollectionViewCell</strong> name <strong>HorizontalCollectionCell</strong> and set this as a subclass for the same in IB.</p><p>6. Add IBOutlet of the label in above collection cell’s subclass. Add below method. Updating the background colour will differentiate cells.</p><pre>func update(index: Int) {<br>   self.titleLabel.text = &quot;\(index) Value&quot;<br>   self.backgroundColor = index % 2 == 0 ? .lightGray : .lightText<br>}</pre><p>7. Coming back to view controller class, add an array variable with an integer type. Initialize the array with some dummy data. Update collections delegate methods as shown below.</p><pre>var items = [1,2,3,4,5]<br>..<br>...</pre><pre>extension ViewController: UICollectionViewDelegate,<br>                          UICollectionViewDataSource {</pre><pre>func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -&gt; Int {<br>   return self.items.count<br>}</pre><pre>func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -&gt; UICollectionViewCell {</pre><pre>   let cell = collectionView.dequeueReusableCell(<br>      withReuseIdentifier: &quot;HorizontalCollectionCell&quot;,<br>      for: indexPath<br>   ) as! HorizontalCollectionCell</pre><pre>   cell.update(index: indexPath.row)<br>   return cell<br>}</pre><p>It should look like this on running the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*7x3Mi6mAKORxUVyjE872uA.png" /></figure><h4>Concept</h4><p>Assuming that reader knows about <strong>contentOffset</strong> and <strong>contentInset</strong>.<br>But actually <strong>contentOffset</strong> is a <strong>CGPoint</strong> aka a pointer which tells the content position in frame from <strong>X</strong> and <strong>Y</strong> direction and <strong>contentInset</strong> is Space/Padding you can give either on <strong>top</strong> and <strong>bottom</strong> in <strong>vertical flow layout</strong> else <strong>left</strong> or <strong>right</strong> in <strong>horizontal flow layout</strong> in the collection view.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fda75JuW2HHuBNqOHHE%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fda75JuW2HHuBNqOHHE%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExY2N0Z3FscDZsNmJjOXF5YWtpbzR1dGd3dWRjZXlzMzhpeHZsb2t0ZiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2Fda75JuW2HHuBNqOHHE%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="339" frameborder="0" scrolling="no"><a href="https://medium.com/media/30ed52cf7cfeaab65e0bca456e3237ea/href">https://medium.com/media/30ed52cf7cfeaab65e0bca456e3237ea/href</a></iframe><p>So depending upon pagination case we will add subview. In that subview there is <strong>UIActivityIndicatorView</strong> or we can say loader, which will rotate when the view will be visible. As shown below the visuals of <strong>refresh all</strong> and <strong>load more</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*RaRNjeW_inJ29zDoLoBUYg.png" /><figcaption>Pull To Refresh i.e. Refresh All</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*zilYnQumWIYM7mibjhv9Rg.png" /><figcaption>Load More</figcaption></figure><p>Let’s began with creating manager class name <strong>HorizontalPaginationManager</strong>. This class will handle pagination actions. It would be good practice to add managers to handle some usual actions. It makes code reusable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f2781b1f42db61bf577dfdd755f3c95/href">https://medium.com/media/4f2781b1f42db61bf577dfdd755f3c95/href</a></iframe><h4>Code Initiation</h4><p>So I’ll explain the step by step</p><ol><li>Add above mention variables in your manager class from <strong>Line no.19–27</strong>.</li><li><strong>isLoading</strong> tells whether loading is going or not. It helps to avoid duplicate requests.</li><li><strong>isObservingKeyPath</strong> helps in observing the change in content offset. It helps to check threshold distance from where we call refresh all or load more. In de-initialiser, the observer is removed.</li><li><strong>scrollView</strong> is taken as a superclass variable Though it is not required. We will add above-mentioned observer on this variable.</li><li><strong>leftmost</strong>/<strong>rightmost</strong> views are the views we will add on the basis of action i.e. left one for refresh all and the right one for load more. This view visibility denotes that action is processing.</li><li>Rest are colours used as per requirement for customisation.</li><li>Add a delegate of type <strong>HorizontalPaginationManagerDelegate</strong>. This need to get te actions which needed to perform while pagination. This protocol consists of two methods as per the actions required. trailing closures are required in order to remove loader views and reset the pagination actions in order to use it again.</li><li><strong>init()</strong> aka initialiser required <strong>scrollView</strong> majorly your collection view.</li></ol><p>Now you have to setup <strong>leftmost</strong>/<strong>rightmost </strong>views as above mentioned, In both the case I have added activity indicator. Set scrollView inset left/right respectively on the basis of view width. Also when the action is performed completely, we have to assign nil and remove from <strong>scrollView</strong> so that we don’t get duplicates.</p><h4>Observing Offset</h4><p>Now you have to override <strong>observeValue</strong> <strong>for keyPath</strong> method like above. Mention key <strong>contentOffset</strong> and set condition for <strong>.new </strong>value so that we will get lastest changed value. On observing we&#39;ll call <strong>setContentOffSet</strong> as mentioned in above. So in that, there will be 2 conditions.</p><ol><li>if <strong>offsetX &lt; -100 &amp;&amp; !self.isLoading</strong>: which means if you dragged beyond <strong>-100</strong> the <strong>threshold</strong> value &amp;&amp; it is not loading then you will perform the action for refresh all and you have to set <strong>self.isLoading</strong> to <strong>true</strong> so it will be called once. Followed by you will call refresh all delegate method in which it’s callback will reset value for loading. It will remove<strong> left most view </strong>and <strong>self.isLoading </strong>to<strong> false</strong>.</li><li>if <strong>contentWidth &gt; frameWidth, offsetX &gt; (diffX + 130) &amp;&amp; !self.isLoading</strong>: which means if you have your <strong>content size</strong> is greater than you <strong>scrollView</strong> <strong>frame size &amp;&amp; </strong>dragged beyond <strong>130</strong> the <strong>threshold</strong> value &amp;&amp; it is not loading then you will perform the action for load more and you have to set <strong>self.isLoading</strong> to <strong>true</strong> so it will be called once. Followed by you will call load more delegate method in which it’s callback will reset value for loading. It will remove<strong> left most view </strong>and <strong>self.isLoading </strong>to<strong> false</strong>.</li><li>The final part is set up pagination in your <strong>ViewController</strong> class.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f105ad60d80c1f630a7fedbca48a99c/href">https://medium.com/media/3f105ad60d80c1f630a7fedbca48a99c/href</a></iframe><p>Here I called <strong>fetchItems</strong> method in <strong>viewDidLoad </strong>as initially, we want to load items initially without pagination actions. Added delay in order to feel like API calls. Like I said earlier refresh all will reset data i.e. sets fresh data and load more append data in the same content.</p><p>I hope you like this tutorial. Feel free to reach out 😄 😄 😄!!!<br><a href="https://www.nickelfox.com/">Nickelfox</a></p><p>Attached Demo Project</p><p><a href="https://github.com/Abhishek9634/HorizontalPaginationDemo">Abhishek9634/HorizontalPaginationDemo</a></p><p>H A P P Y — C O D I N G 😄 😄 😄!!!</p><p>Here is my other two recent stories…</p><ul><li><a href="https://medium.com/nickelfox/ios-swift-expandable-textview-with-placeholder-fca5ed2556f4">iOS Swift Expandable TextView with Placeholder</a></li><li><a href="https://medium.com/nickelfox/ios-swift-custom-tabbarcontroller-with-tab-item-animation-b26f6a6e2c62">iOS Swift Custom TabBarController with Tab Item Animation</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=13ba1e4d21ef" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/ios-swift-uicollectionview-with-horizontal-pagination-13ba1e4d21ef">iOS Swift UICollectionView With Horizontal Pagination</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What actually you learned from a project accomplishment? (2/2)]]></title>
            <link>https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-2-2-78513b2f48a5?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/78513b2f48a5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[dropdown]]></category>
            <category><![CDATA[features]]></category>
            <category><![CDATA[alertdialog]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Wed, 03 Apr 2019 17:45:28 GMT</pubDate>
            <atom:updated>2019-04-04T08:45:25.224Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*NMgmoRDeJb9tpZih.jpg" /></figure><p>In the <a href="https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-1-2-f8e10194656d">previous</a> story I have discussed about the major bugs solved. On continuing with that, I will share the some small features developed by my own. I know that these are simple and already many libraries are available. But it’s all about your efforts how you are curious to do things by own.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F6ul9g1rMhfLH2%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F6ul9g1rMhfLH2%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F6ul9g1rMhfLH2%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="380" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b24944e6ae5aecaef64ebd7e9e7d333/href">https://medium.com/media/8b24944e6ae5aecaef64ebd7e9e7d333/href</a></iframe><p>😅😅😅 Yep !!! Let’ start…</p><h3>Features</h3><h4>1. Progress Bar</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*H3vIZ-_jqxiqkJ_MEohb9w.png" /></figure><p>Using default <strong>UISlider</strong> can’t be customised this much. So, I made a custom class <strong>ProgressBar</strong>. In this I have add subview (the blue highlighted one above). Added <strong>@IBInspectable</strong> properties so that we can customise from storyboard directly rather programatically.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8bdd71b01b260c5d69cd047368c030c/href">https://medium.com/media/c8bdd71b01b260c5d69cd047368c030c/href</a></iframe><p>Progress aka highlighted view ‘s width is calculated on the basis of min &amp; max values. Now simple drag a <strong>UIView</strong> in storyboard, set custom class and see the magic.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3o84U6421OOWegpQhq%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3o84U6421OOWegpQhq%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3o84U6421OOWegpQhq%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="245" frameborder="0" scrolling="no"><a href="https://medium.com/media/5923d99a20c40852ac87a37ceddaddc7/href">https://medium.com/media/5923d99a20c40852ac87a37ceddaddc7/href</a></iframe><p><strong>Usage:</strong></p><pre>@IBOutlet weak var progressBar: ProgressBar!</pre><pre>self.progressBar.sliderValue = CGFloat(integerLiteral: 70))<br>self.progressBar.maxValue = CGFloat(integerLiteral: 100))</pre><h4>2. Custom Local Notification Banner</h4><p>Usually what we use <strong>UIAlertController</strong> to popup message, user atleast needed to press ok to dismiss. I also use that but in some cases it’s actually not necessary. A thought came to my mind that why don’t I make some thing that prompt and dismiss automatically like other apps do, as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0aiWSzifAK8auFw_X9pmAw.png" /><figcaption>Custom Notification OR SnackBar</figcaption></figure><p>So I create a new <strong>UIView</strong> with custom class <strong>SnackBar</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQLG2nYuGq_kWiMotuhf7Q.png" /></figure><p>Dragged <strong>titleLabel </strong>and added <strong>UIViewController’s</strong> extension so that I can call from any view controller. But the major thing where I stuck is how can I will prompt in any view-controller. Luckily I got answer from stack-overflow about floating object in any view i.e. using <strong>UIWindow</strong> &amp; Apple already provide window object in <strong>AppDelegate</strong> class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b839072c480f3997031fe24fded5dc37/href">https://medium.com/media/b839072c480f3997031fe24fded5dc37/href</a></iframe><p>Using window object, I have added snackbar view as subview and added animation i.e <strong><em>UIView.animation (…) { } and play with alpha value </em></strong>to feels like local notification. You can also do with manual constraint to get actual notification feel.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F1iqrWXSSrhqxO%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F1iqrWXSSrhqxO%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F1iqrWXSSrhqxO%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/fbcdcb55513ad69fcc33f4cd75a93d5a/href">https://medium.com/media/fbcdcb55513ad69fcc33f4cd75a93d5a/href</a></iframe><p><strong>Usage:</strong></p><pre>self.showSnackBar(msg: &quot;Your Data is successfully updated!!!&quot;,<br>                  delay: 1.0)</pre><h4>3. Drop Down Menu</h4><p>Well dropdown is something which iOS don’t actually use, instead they default picker, which is very weird as compare to latest iOS UI. Hence we opt a library. It’s good to use library when required in multiple screens but not of single screen in my opinion. As per requirement I needed as shown below. At that time I need exactly like this but due customisation limit I failed and eventually I developed my own.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J_aMX_AA2JZR4_lnIweJSQ.png" /><figcaption>Custom Drop Down Menu</figcaption></figure><p>I dragged a <strong>UIView </strong>and added <strong>UITableView</strong> as subview in my ViewController, assigned <strong>DropDownView</strong> as custom class with outlet.</p><pre>@IBOutlet weak var dropDownView: DropDownView!</pre><p>Added a <strong>UIView</strong> in bottom as separator with height constraint to 1. The Upper consist a label which show selected option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EPr9TeBrP1Izoqd59ENw0Q.png" /></figure><p>That’s the Option table cell UI with title and marker. This will be visible to selected option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*SZCdoLoRkaOYZJjnp86XXw.png" /></figure><p><strong>DropDownTableViewCell</strong> is the custom class of above option cell UI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b47ccfab8746d1ae213712288dc6c613/href">https://medium.com/media/b47ccfab8746d1ae213712288dc6c613/href</a></iframe><p><strong>DropDownCellModel</strong> is cell model which consist option type (<strong>PerformanceDateGroup</strong>) and <strong>selected</strong> state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f00493f294288fe8847d73b6655b1157/href">https://medium.com/media/f00493f294288fe8847d73b6655b1157/href</a></iframe><p>Now as per requirement 3 options needed — daily, weekly and monthly.<br>Created enum <strong>PerformanceDateGroup </strong>options cases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a21ec18b394500c8fbfcbf0a9d901fe5/href">https://medium.com/media/a21ec18b394500c8fbfcbf0a9d901fe5/href</a></iframe><p>Above class is DropDownView which consist</p><p>1.<strong> OptionTableView’s</strong> <strong>delegates</strong> and <strong>dataSources</strong>.</p><p>2. <strong>setupGesture()</strong> which is added to selected label. On tap of which it calls <strong>toggleMenu()</strong> method to show/hide drop down.</p><p>3. <strong>handleFilterSelection() </strong>decorates that cell which is selected by user.</p><p>4. On selecting option, it call’s it’s delegate method <strong>didSelect(…)</strong>, which perform action in conforming ViewController.</p><p><strong>Usage:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f7e2a3cbdd55f5c7eb8ecfa3d1970b8b/href">https://medium.com/media/f7e2a3cbdd55f5c7eb8ecfa3d1970b8b/href</a></iframe><ol><li><strong>setupDropDown() </strong>will setup dropdown cell models and delegate.</li><li><strong>setupData()</strong> works first time to handle your data first time in which date option are using as filter.</li><li><strong>hideOnOtherView() </strong>handles whether user taps outside the dropdown. It will hide if drop down is visible.</li></ol><p><strong>I hope you enjoyed the story and hopefully start developing things by own.</strong> 👏👏👏<br><strong>Your one single effort can change the things into another level </strong>🎉🎉🎉</p><p>See you soon👋👋👋!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78513b2f48a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-2-2-78513b2f48a5">What actually you learned from a project accomplishment? (2/2)</a> was originally published in <a href="https://medium.com/nickelfox">Nickelfox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What actually you learned from a project accomplishment? (1/2)]]></title>
            <link>https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-1-2-f8e10194656d?source=rss-77bba74aca88------2</link>
            <guid isPermaLink="false">https://medium.com/p/f8e10194656d</guid>
            <category><![CDATA[bug-fixes]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abhishek Thapliyal]]></dc:creator>
            <pubDate>Tue, 02 Apr 2019 10:35:18 GMT</pubDate>
            <atom:updated>2019-04-04T08:44:52.743Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/694/0*LQjKivAVdTU-HmZL.png" /></figure><p>Generally app developers works on different projects and say that <em>this is the same project as earlier &amp; I have done nothing new</em>. But it’s not all about putting <strong>UIViewController </strong>or<strong> UITableView</strong>. There is always a small new feature or new type type of bug fixes which increase your skills and confidence. So In this story I will share my learnings on recent projects accomplishment. I know it’s not big thing to write but that’s make me to share to all of you.</p><h3>Bug Fixes</h3><h4>1. UITableView fluctuation on reloadData()</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FzhmIHStBa2ezu%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FzhmIHStBa2ezu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FzhmIHStBa2ezu%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="327" frameborder="0" scrolling="no"><a href="https://medium.com/media/915262b4d7da2df1a1138a07b4cdc3d5/href">https://medium.com/media/915262b4d7da2df1a1138a07b4cdc3d5/href</a></iframe><p>This is the case when you have different types of cell with dynamic height. So in general what we do, Hit <strong>HTTP </strong>Request, generate cell models and reloadData(). Now you have observe in some case it fluctuates on reload, even though you add row height delegates.</p><pre>func tableView(_ tableView: UITableView,<br>               heightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>     return UITableViewAutomaticDimension<br>}</pre><pre>func tableView(_ tableView: UITableView,<br>               estimatedHeightForRowAt indexPath: IndexPath) -&gt; CGFloat {<br>     return 44.0<br>}</pre><p>So what’s wrong with that.</p><p>The actual cause of fluctuation is hard coded value in estimated size aka <strong>44.0</strong>. Your cell needs atleast min height 150.0 and estimated is 44.0, It will try to gain space in runtime while reloading, which cause fluctuation. So instead of placing hardcoded value, use a referenced value</p><pre>tableView.bounds.height / 2</pre><p>This value will provide enough reserved height to cell to expand and adjust as per requirement. Hence, fluctuation f***g gone :).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5w095rI0BpUUKHcyvd%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5w095rI0BpUUKHcyvd%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5w095rI0BpUUKHcyvd%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="295" frameborder="0" scrolling="no"><a href="https://medium.com/media/835230557f2fc59c9c2f82b4bc01d616/href">https://medium.com/media/835230557f2fc59c9c2f82b4bc01d616/href</a></iframe><h4>2. UITableViewController with static cells fluctuation on textfields become first Responder.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FmuL2iYJR1MNPCdXxHv%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FmuL2iYJR1MNPCdXxHv%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FmuL2iYJR1MNPCdXxHv%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b06038f9403df50dce7c135262447bd/href">https://medium.com/media/1b06038f9403df50dce7c135262447bd/href</a></iframe><p>In the recent iOS ≥11 versions, I have faced this issue many times . What actually happens is when you add static cells and put some <strong>UITextField</strong> or <strong>UITextView</strong>,<strong> </strong>and you tap on textfield, keyboard appears and table goes up and down. Hence I have to remove <strong>UITableViewController </strong>and add <strong>UIViewController</strong> with <strong>UITableView</strong> manually like earlier. That was a lazy moment me to do duplicate task. So this time i made to fix/work around for the issue. I broke the task into 2 parts</p><p><strong>A: Stop automatic offset change<br></strong>I got an answer from stack-overflow that if we override <strong>viewWillAppear</strong> and <strong>DON’T</strong> call it’s <strong>super method</strong>, it will stop changing tableView’s content offset.</p><pre>override viewWillAppear(_ animated: Bool) {<br>    // DON&#39;T CALL SUPER METHOD<br>}</pre><p><strong>B: Set custom offset so that textfield is visible<br></strong>Now, with one problem is fixed, I needed default behaviour too. For that I have add two notifications - <strong>UIKeyboardWillShow</strong> &amp; <strong>UIKeyboardWillHide — </strong>and added array of all input fields and contentOffset to store value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9c5311acfc49bb9442b8950faa9544ff/href">https://medium.com/media/9c5311acfc49bb9442b8950faa9544ff/href</a></iframe><p>So now, whenever keyboard is about to appear, it’s notification handler saves current offset, and check firstResponder view. On the basis of location in superview, update tableView’s offset. Then when keyboard is about to disappear, reset the offset. So, without fluctuation I was able to achieve the requirement.</p><h4>3. APNS Redirection on Background Modes</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl0MYKCdwRKsMsKNsA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl0MYKCdwRKsMsKNsA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl0MYKCdwRKsMsKNsA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="433" frameborder="0" scrolling="no"><a href="https://medium.com/media/6878955053894df454b0b03dc8c67b9e/href">https://medium.com/media/6878955053894df454b0b03dc8c67b9e/href</a></iframe><p>I have a common scenario to open a view on user tap on notification.<br>But usually what we do is to request notification and put delegates</p><pre>extension AppDelegate: UNUserNotificationCenterDelegate {</pre><pre>func registerForPushNotifications() {<br>    let center = UNUserNotificationCenter.current()<br>    center.requestAuthorization(<br>       options: [.badge, .alert, .sound]<br>    ) { (flag, error) in<br>        if flag {<br>            DispatchQueue.main.async {<br>               UIApplication.shared.registerForRemoteNotifications()<br>            }<br>        }<br>    }<br>}</pre><pre>func userNotificationCenter(_ center: UNUserNotificationCenter,<br>            willPresent notification: UNNotification,<br>            withCompletionHandler completionHandler:<br>    <a href="http://twitter.com/escaping">@escaping</a> (UNNotificationPresentationOptions) -&gt; Void) {<br>        <br>    let userInfo = notification.request.content.userInfo <br>    print(&quot;APNS willPresent: \(userInfo)&quot;)<br>    completionHandler([.badge, .alert, .sound])<br>}</pre><pre>func userNotificationCenter(_ center: UNUserNotificationCenter,<br>            didReceive response: UNNotificationResponse,<br>    withCompletionHandler completionHandler: <a href="http://twitter.com/escaping">@escaping</a> () -&gt; Void) {</pre><pre>    let userInfo = response.notification.request.content.userInfo<br>    print(&quot;APNS didReceive: \(userInfo)&quot;)<br>    completionHandler()<br>}</pre><pre>}</pre><p>The code seems to be fine but it wasn’t calling above two delegates. I spent a lot of time to find the solution. Many stack-overflow answers told use old notification methods used in iOS &lt; 10. I tried that too but not fulfil my requirement to handle separate user tap or just app open from home.</p><p>The actual solution is</p><pre>center.delegate = self</pre><p>Although i have conformed the delegate but not set <strong>self</strong>, which is why when notification arrived, it called upon the older method not above those. With this solution, it works like a charm now.</p><p>That’s all for now. <br><br>A little extra time spent, a little trial and error, and not being afraid to ask questions, led me to learn something new, and improve my own methods and productivity. I encourage you to do the same.</p><p>In the next blog, I’d love to share a few things I developed on my own.</p><h4>Stay tuned 😃😃😃!!!</h4><h4>Update</h4><p>The feature blog is <a href="https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-2-2-78513b2f48a5">here</a>…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f8e10194656d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/nickelfox/what-actually-you-learned-from-a-project-accomplishment-1-2-f8e10194656d">What actually you learned from a project accomplishment? (1/2)</a> was originally published in <a href="https://medium.com/nickelfox">Nickelfox</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>