<?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 Timotius Leonardo Lianoto on Medium]]></title>
        <description><![CDATA[Stories by Timotius Leonardo Lianoto on Medium]]></description>
        <link>https://medium.com/@lionato14?source=rss-3a70217b11c0------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qH-9BavirjggwjlZdcbnPA.jpeg</url>
            <title>Stories by Timotius Leonardo Lianoto on Medium</title>
            <link>https://medium.com/@lionato14?source=rss-3a70217b11c0------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:28:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lionato14/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[Remote Config (x) Property Wrapper — SWIFT]]></title>
            <link>https://engineering.idn.media/remote-config-x-property-wrapper-swift-666347fdc5c9?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/666347fdc5c9</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[advancedswift]]></category>
            <category><![CDATA[firebase-remote-config]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Mon, 24 Mar 2025 15:14:02 GMT</pubDate>
            <atom:updated>2025-03-24T15:14:02.451Z</atom:updated>
            <content:encoded><![CDATA[<h3>Remote Config (x) Property Wrapper — SWIFT</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*55_RnUfCchl7woOB2YwPeA.png" /></figure><p>This is a continuation of my last Medium story, which you can find at:</p><p><a href="https://medium.com/idn-engineering/mock-your-remote-config-5e614553590e">Mock Your Remote Config</a></p><p>For those of you who are new to this story and want to understand the background and purpose behind developing the Remote Config code for our app, I recommend reading the previous article first.</p><p>Without further ado, let’s dive into the details!</p><h3>Background</h3><p>Initially, I thought the Remote Config helper I built in my last story was sufficient. However, after using it in several projects, I encountered a few issues:</p><ol><li>Every time we retrieve data through the helper, we need memory to parse the JSON from Remote Config. This is evident in the startRemoteConfigV3 code. The larger the JSON data in Remote Config, the more memory it consumes.</li><li>The JSON string isn’t actually used in our app (only in unit tests), which can be confusing for other developers.</li><li>Testing relies on JSON strings. If the Remote Config model changes in type or CodingKey name, we must manually find and update any unit tests that still using outdated string keys.</li><li>Every time we create a new class, we must manually inject MockRemoteConfig(). If we have 1,000 classes, this becomes a repetitive and inefficient task.</li></ol><p>These are just some of the issues, and there are many more when examined in detail. In this story, we will explore solutions to address these problems.</p><h3>FirebaseConfig Helper</h3><p>To resolve the above issues, we will create a new property wrapper struct called FirebaseConfig. But First we should create our RemoteConfig protocol and also its class object to save cached data in shared object.</p><pre>protocol RemoteConfigProtocol: AnyObject {<br>    var cachedRemoteConfigItem: IDNCache&lt;String, Any?&gt; { get }<br>}<br><br>class MediumRemoteConfig: IDNRemoteConfigProtocol {<br>    static var shared = MediumRemoteConfig()<br>    <br>    var cachedRemoteConfigItem = IDNCache&lt;String, Any?&gt;()<br>}</pre><pre>@propertyWrapper<br>struct FirebaseConfig&lt;T: Codable&gt; {<br>    var _MediumRemoteConfig: IDNRemoteConfigProtocol = MediumRemoteConfig.shared<br>    <br>    /// Contains a saved value from last fetching.<br>    private var cachedValue: T? {<br>        _MediumRemoteConfig.cachedRemoteConfigItem[label] as? T<br>    }<br>    private var label: String<br>    var wrappedValue: T? {<br>        if let cachedValue {<br>            return cachedValue<br>        }<br>        <br>        let remoteConfig = RemoteConfig.remoteConfig()<br>        let value = remoteConfig.configValue(forKey: label)<br>        print(&quot;[FirebaseConfig]: \(label) \(value.stringValue ?? &quot;-&quot;)&quot;)<br>        <br>        if let jsonData = value.stringValue?.data(using: .utf8),<br>           let config = try? JSONDecoder().decode(T.self, from: jsonData) {<br>            _MediumRemoteConfig.cachedRemoteConfigItem[label] = config<br>            return config<br>        }<br>        <br>        return nil<br>    }<br>    <br>    /// &quot;Initialization for property wrapper&quot;<br>    /// - Parameter label: insert label using provided enum. please add one in IDNRemoteConfig if want to subscribe to new remote config.<br>    init(_ label: String) {<br>        self.label = label<br>    }<br>}</pre><h4>Understanding Property Wrappers</h4><p>For those unfamiliar with property wrappers, I recommend reading this concise and well-explained resource: <a href="https://www.swiftbysundell.com/articles/property-wrappers-in-swift/">Property Wrappers in Swift</a>.</p><p>In short, a propertyWrapper object only exposes access to its wrappedValue property. This allows us to implement custom logic whenever another object retrieves the value of the wrappedValue variable.</p><h4>Code Explanation</h4><ol><li>Inside wrappedValue, we first check the cachedValue variable to see if the Remote Config value has already been stored in the current user session. If it has, we return the cached data immediately without re-parsing the JSON string from Remote Config.</li><li>If cachedValue is not found, we follow the existing process—parsing the JSON string into the desired model. We also make sure to store this value in the app&#39;s cache.</li><li>The init() function takes a parameter—the name of the Remote Config key to fetch as a String.</li><li>I will not add IDNCache to this article, because i am afraid our story here becomes too long and too broad. Just implement simple cache using NSCache is okay or if you want to make a similar code like me you can go to this <a href="https://www.swiftbysundell.com/articles/caching-in-swift/">article</a>.</li><li>Implement var for shared instance MediumRemoteConfig is BAD! but JUST for tutorial, allow me to continue with this code okay? 😂 beg your apologize, but i will explain this later.</li></ol><h3>FirebaseConfig Usage</h3><p>Using FirebaseConfig is incredibly simple! Take a look at the following example:</p><pre>@FirebaseConfig(&quot;fill_your_config_name_here&quot;) var appSettingRemoteConfig: RemoteConfigAppSetting?</pre><pre>struct RemoteConfigAppSetting: Codable {<br>    var appName: String<br>}</pre><p>Yes, that’s all it takes to fetch data from Remote Config! The value inside wrappedValue is automatically returned and assigned to the class’s variable—in this case, appName.</p><h3>Code Explanation</h3><ol><li>The logic inside wrappedValue only runs when Remote Config is accessed. This makes it more efficient and safer compared to assigning data using a regular setter like var name = &quot;timo&quot;, which prevents real-time updates (more on this in the next section).</li></ol><h3>FirebaseConfig With Real-Time updates handling</h3><p>You might be wondering, how do we handle real-time updates when Remote Config changes in Firebase? With this approach, we actually manage updates better than injecting values into variables! Let me show you an example. We will add this function to our MediumRemoteConfig .</p><pre>private func setListenerToUpdatedConfig() {<br>        let remoteConfig = RemoteConfig.remoteConfig()<br><br>        remoteConfig.addOnConfigUpdateListener { configUpdate, error in<br>            guard let configUpdate, error == nil else {<br>                print(&quot;[FirebaseRemoteConfig] Error listening for config updates: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>                return<br>            }<br>            <br>            print(&quot;[FirebaseRemoteConfig] Updated keys: \(configUpdate.updatedKeys)&quot;)<br>            <br>            self.remoteConfig.activate { [weak self] changed, error in<br>                guard error == nil else {<br>                    return print(&quot;[FirebaseRemoteConfig] fail to activate updated remote config, error: \(error?.localizedDescription ?? &quot;&quot;)&quot;)<br>                }<br>                <br>                print(&quot;[FirebaseRemoteConfig] success to activate updated remote config!)&quot;)<br>                <br>                print(&quot;[FirebaseRemoteConfig] remove updated keys from app cache!)&quot;)<br>                for key in configUpdate.updatedKeys {<br>                    self?.cachedRemoteConfigItem.removeValue(forKey: key)<br>                }<br>            }<br>        }<br>    }</pre><p>The above code enables real-time updates from Firebase, right? We clear the cache from the shared instance in MediumRemoteConfig, ensuring that when @FirebaseConfig runs, users instantly receive the latest values.</p><h3>FirebaseConfig Testing</h3><p>Testing is also straightforward. Remember the _MediumRemoteConfig: RemoteConfigProtocol? variable from the FIREBASECONFIG HELPER section? Here, we use its cachedRemoteConfigItem property to mock Remote Config more effectively.</p><p>First we will change our MediumRemoteConfig shared instance to Mock Instance:</p><pre>class MockMediumRemoteConfig: RemoteConfigProtocol {<br>    var cachedRemoteConfigItem = IDNCache&lt;String, Any?&gt;()<br>}<br><br>MediumRemoteConfig.shared = MockMediumRemoteConfig()</pre><pre>import XCTest<br><br>class AppUnitTest: XCTestCase {<br><br>      func testAppName() {<br>          MediumRemoteConfig.shared.cachedRemoteConfigItem[&quot;fill_your_remote_config_name_here&quot;] = RemoteConfigAppSetting(<br>              appName: &quot;IDN Livestream&quot;<br>          )<br>      <br>          ...<br>      }<br>}</pre><p>With this approach, we achieve a cleaner, more efficient, and testable Remote Config integration in our app. You don’t need to be afraid anymore to write the wrong JSON String for mocking or jump back and forth to Firebase Console Dashboard to search for the right JSON to use because XCode will aid you to find it 👀.</p><p>Code Explanation:</p><ol><li>Make sure to change MediumRemoteConfig.shared = MockMediumRemoteConfig() ONLY when you first run UnitTesting environment to prevent any unnecessary code in our app codebase.</li><li>If you don’t want to create mock class its okay also, because when you finish run your unit test, your app will be going to force close and your cache will disappear like ashes.</li></ol><blockquote>Actually in my actual code that i used in my app, i recommend to use another PropertyWrapper to inject instance to _MediumRemoteConfig in FirebaseConfig propertyWrapper (DepedencyInjection like Swinject), So we wouldn’t have to make mutable shared property like in MediumRemoteConfig class.<br>But i won’t cover it also in this story to avoid any unrelated topic, instead i will tell you about it in the next story to make it more detailed.</blockquote><p>Hope this story will help you to improve your RemoteConfig implementation in your app. Don’t forget to like and comment to this story to support me write and uncover more about Swift and iOS things 😊.</p><p>Have a great day and Happy Coding everyone! God bless you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=666347fdc5c9" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/remote-config-x-property-wrapper-swift-666347fdc5c9">Remote Config (x) Property Wrapper — SWIFT</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mock Your Remote Config‍]]></title>
            <link>https://engineering.idn.media/mock-your-remote-config-5e614553590e?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e614553590e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[firebase-remote-config]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Wed, 27 Nov 2024 11:35:11 GMT</pubDate>
            <atom:updated>2024-11-27T11:35:11.057Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dSJh3XepPd6Fx9jjuwHgdA.png" /></figure><p>Firebase Remote Config is a common feature in many applications, enabling developers to change values, update navigation, and much more — all in real-time. While Firebase isn’t the only service that offers such functionality, the underlying concept remains largely the same.</p><p>For many developers (myself included), testing code that integrates Remote Config is often overlooked. Early in my journey as a Swift/iOS developer, I didn’t pay much attention to it. However, as the apps I worked on grew more complex, I realized the importance of testing every piece of code — including those that depend on Remote Config.</p><p>Around 1–2 years ago, I started searching for a way to test Remote Config effectively, and surprisingly, it wasn’t as difficult as I had imagined! In this article, I’ll share my findings and demonstrate a simple, abstract approach you can adapt or improve to make Remote Config testing part of your workflow.</p><h3>1. Creating a Remote Config Helper</h3><p>Most of us already have a helper class for managing Remote Config, whether as a singleton or something else. We won’t dive deeply into its implementation here, but let’s assume you have a function that serves as the basis for our example.</p><pre>class RemoteConfigHelper {<br>    let remoteConfig = RemoteConfig.remoteConfig()<br>    static let shared = RemoteConfigHelper()<br>    <br>    private init() {}<br>    <br>    func startRemoteConfigV3&lt;T: Codable&gt;(label: String) -&gt; T? {<br>        let value = remoteConfig.configValue(forKey: label.rawValue)<br>        <br>        if let jsonData = value.stringValue?.data(using: .utf8),<br>           let config = try? JSONDecoder().decode(T.self, from: jsonData) {<br>            return config<br>        }<br>        <br>        return nil<br>    }<br>}</pre><h3>2. Leveraging Protocols: The Secret to Mocking</h3><p>Swift embraces protocol-oriented programming, and using protocols makes creating mock classes significantly easier. We’ll create a simple mock class that mimics the behavior of your Remote Config helper class. This abstraction ensures that your production code and test code remain decoupled.</p><p>Here’s how you can define a protocol to guide your implementation:</p><pre>protocol RemoteConfigHelperSpecs {<br>    func startRemoteConfigV3&lt;T: Codable&gt;(label: String) -&gt; T?<br>}</pre><pre>protocol RemoteConfigHelperSpecs {<br>    func startRemoteConfigV3&lt;T: Codable&gt;(label: String) -&gt; T?<br>}<br><br>class RemoteConfigHelper: RemoteConfigHelperSpecs {<br>    let remoteConfig = RemoteConfig.remoteConfig()<br>    static let shared = RemoteConfigHelper()<br>    <br>    private init() {}<br>    <br>    func startRemoteConfigV3&lt;T: Codable&gt;(label: String) -&gt; T? {<br>        let value = remoteConfig.configValue(forKey: label.rawValue)<br>        <br>        if let jsonData = value.stringValue?.data(using: .utf8),<br>           let config = try? JSONDecoder().decode(T.self, from: jsonData) {<br>            return config<br>        }<br>        <br>        return nil<br>    }<br>}</pre><h3>3. Dependency Injection in Your Remote Config-Dependent Classes</h3><p>To integrate this protocol into your codebase, you’ll need to adopt dependency injection. This technique replaces direct calls to your helper class with injected instances that conform to the protocol. Let’s look at an example of dependency injection in action:</p><pre>class MediumPresenter {<br>  var _RemoteConfig: RemoteConfigHelperSpecs<br>  var myNameFromRemoteConfig: String? // will be used to for our unit testing<br><br>  init(remoteConfigHelper: RemoteConfigHelperSpecs) {<br>        self._RemoteConfig = remoteConfigHelper<br>    }<br><br>  func getRemoteConfig() {<br>      let model: RemoteConfigWhitelistLink? = _RemoteConfig.startRemoteConfigV3(label: &quot;name_remote_config&quot;)<br>      linksFromRemoteConfig = model?.domains <br>  }<br>}</pre><pre>class RemoteConfigWhitelistLink: Codable {<br>    var domains: [String]?<br>    <br>    private enum CodingKeys: String, CodingKey {<br>        case domains<br>    }<br>}</pre><h3>4. Mocking the Remote Config Helper</h3><p>Next, create a mock class that conforms to your RemoteConfigSpecs protocol. This mock class is crucial for isolating your tests from Firebase’s actual Remote Config backend. Here’s a simplified example:</p><pre>class MockRemoteConfigHelper: RemoteConfigHelperSpecs {<br>        var jsonString: String?<br>        <br>        func startRemoteConfigV3&lt;T&gt;(label: String) -&gt; T? where T : Decodable, T : Encodable {<br>            if let jsonData = jsonString?.data(using: .utf8) {<br>                do {<br>                    let config = try JSONDecoder().decode(<br>                        T.self,<br>                        from: jsonData<br>                    )<br>                    return config<br>                } catch {}<br>            }<br>            return nil<br>        }<br>    }</pre><p>By adding a jsonString variable, you can define the JSON data that mimics what you’d typically receive from Remote Config. This flexibility allows you to simulate various scenarios in your tests.</p><h3>5. Time to Test!</h3><p>The testing phase is the moment of truth. Use your preferred testing framework (such as XCTest or Swift Testing) to validate how your application handles different Remote Config values.</p><p>Here’s how you might inject your mock into a test case:</p><pre>func testMediumPresenter() {<br>    let mockRemoteConfig = MockRemoteConfigHelper()<br>    mockRemoteConfig.jsonString = &quot;&quot;&quot;<br>    {<br>        &quot;domains&quot;: [<br>                &quot;www.google.com&quot;,<br>                &quot;www.idntimes.com&quot;<br>              ]<br>    }<br>    &quot;&quot;&quot;<br>    <br>    // Create medium presenter with mockRemoteConfig injection<br>    let mediumPresenter = MediumPresenter(remoteConfigHelper: mockRemoteConfig)<br>    mediumPresenter.getRemoteConfig()<br>      <br>      <br>    XCTAssertEqual(mediumPresenter.linksFromRemoteConfig?.count, 2)<br>}</pre><p>How is it? it should return success right now. So when you want to test with another cases we can just re-configure the jsonString variable within our XCTest classes.</p><h3>Conclusion</h3><p>Firebase Remote Config is a powerful tool, but it often goes untested — potentially leading to major issues as your app scales. By adopting Protocol-Oriented Programming and implementing mocks, you can confidently test your Remote Config integration and future-proof your codebase.</p><p>The approach shared here is the result of personal experimentation, so there may be room for improvement. If you have suggestions or alternative ideas, feel free to share them in the comments. Let’s learn and grow together as developers.</p><p>Happy Coding! 🧑‍💻</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e614553590e" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/mock-your-remote-config-5e614553590e">Mock Your Remote Config🧑‍💻</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streamlining NotificationCenter Usage in Swift]]></title>
            <link>https://engineering.idn.media/streamlining-notificationcenter-usage-in-swift-a21a83704290?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/a21a83704290</guid>
            <category><![CDATA[advancedswift]]></category>
            <category><![CDATA[notification-center]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Thu, 08 Aug 2024 15:55:29 GMT</pubDate>
            <atom:updated>2024-08-08T15:55:29.508Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CKt3Y4C94_dvDRX191n28g.png" /><figcaption>Notification Center Background</figcaption></figure><p>If you’re a Swift developer, NotificationCenter is probably no stranger to you, right? We often use this syntax to trigger functions in our class objects without having to reference other objects directly.</p><p>Personally, I’m not a huge fan of NotificationCenter. Here’s why:</p><ul><li>It’s tough to trace who’s observing a notification with a specific ID.</li><li>It’s equally difficult to pinpoint which object is posting the notification with that ID.</li><li>And let’s not forget how challenging it is to unit test NotificationCenter in those objects.</li></ul><p>That said, NotificationCenter can be a real time-saver for us developers (especially for those who might be a bit too lazy to follow architectural best practices 🤣). It helps us break free from object references, reducing the number of variables in an object and allowing us to broadcast to more than one object at a time.</p><p>So, in my opinion, NotificationCenter is a double-edged sword. When used correctly, we can mitigate the downsides mentioned above.</p><p>Do you agree with that? If you’ve encountered these issues too, you’re in the right place. In this article, we’ll tackle these three problems using a protocol I’ve named <strong>NotificatorSpecs</strong>. Let’s dive in!</p><h3>Crafting the NotificatorSpecs Protocol</h3><pre>public protocol NotificatorSpecs {<br>    var components: NotificatorSpecsComponents { get }<br>    <br>    /// Return a publisher.<br>    /// Can be used for SwiftUI implementation to receive value from NotificationCenter<br>    ///<br>    /// - Parameter type: NotificatorNameType enums<br>    /// - Returns: NotficationCenter&#39;s Publisher<br>    func observe(type: NotificatorNameType) -&gt; NotificationCenter.Publisher<br>    <br>    /// A void function to subscribe to a NotificationCenter.<br>    ///<br>    /// - Parameter type: NotificatorNameType enums<br>    /// - Parameter observer: an object that observing to this notifcation<br>    /// - Parameter completion: A Selector that will be called when Notification is Notified<br>    func observe&lt;Observer: NSObject&gt;(type: NotificatorNameType,<br>                                     observer: Observer,<br>                                     completion: Selector)<br>    <br>    /// same with observe(), but this is for multi-observe use<br>    func observe&lt;Observer: NSObject&gt;(types: [NotificatorNameType: (observer: Observer, completion: Selector)])<br>    <br>    /// A void function to trigger the observers of a NotificationCenter.<br>    func notify(type: NotificatorNameType,<br>                object: Any?,<br>                userInfo: [AnyHashable: Any]?)<br>    <br>    /// Function to stop observing to a NotificationCenter.<br>    /// # Notes: #<br>    /// This function should be called when a notificationCenter is not needed anymore.<br>    func stopObserve&lt;Observer: NSObject&gt;(type: NotificatorNameType,<br>                                         observer: Observer,<br>                                         object: Any?)<br>}<br><br>public extension NotificatorSpecs {<br>    func observe(type: NotificatorNameType) -&gt; NotificationCenter.Publisher {<br>        NotificationCenter.default.publisher(for: type.name)<br>    }<br>    <br>    func observe&lt;Observer: NSObject&gt;(type: NotificatorNameType,<br>                                     observer: Observer,<br>                                     completion: Selector) {<br>        NotificationCenter<br>            .default<br>            .addObserver(observer,<br>                         selector: completion,<br>                         name: type.name,<br>                         object: nil)<br>        components.changeObservers(type: type,<br>                                   observer: observer)<br>    }<br>    <br>    func observe&lt;Observer: NSObject&gt;(types: [NotificatorNameType: (observer: Observer, completion: Selector)]) {<br>        for type in types {<br>            observe(type: type.key,<br>                    observer: type.value.observer,<br>                    completion: type.value.completion)<br>        }<br>    }<br>    <br>    func notify(type: NotificatorNameType,<br>                object: Any? = nil,<br>                userInfo: [AnyHashable: Any]? = nil) {<br>        NotificationCenter<br>            .default<br>            .post(name: type.name,<br>                  object: object,<br>                  userInfo: userInfo)<br>    }<br>    <br>    func stopObserve&lt;Observer: NSObject&gt;(type: NotificatorNameType,<br>                                         observer: Observer,<br>                                         object: Any? = nil) {<br>        NotificationCenter<br>            .default<br>            .removeObserver(observer,<br>                            name: type.name,<br>                            object: object)<br>        components.deleteObserver(type: type)<br>    }<br>    <br>    /// If there is 1 or more observers, this function will stop all the observer<br>    func stopAllObserver() {<br>        guard !components.observers.isEmpty else {<br>            return<br>        }<br>        <br>        components.observers.forEach { collection in<br>            print(&quot;Removed notification observer \(collection.key.name)&quot;)<br>            NotificationCenter<br>                .default<br>                .removeObserver(collection.value,<br>                                name: collection.key.name,<br>                                object: nil)<br>            components.deleteObserver(type: collection.key)<br>        }<br>    }<br>}</pre><p>We’ve created a protocol that we’ll be using going forward. But why did we opt for a protocol instead of a parent class? Well, according to Swift’s documentation, Swift is designed with the principles of Protocol-Oriented Programming (POP) in mind. Beyond that, this protocol will be incredibly useful when it comes to testing our helper classes down the line.</p><p>Now, why did we create an extension? The extension will be handy if we want to have a single function shared across multiple helpers that manage our notifications. However, using an extension is entirely optional and depends on the needs of your specific project.</p><h3>Creating the NotificatorSpecsComponents</h3><p>When you try to run the code, you’ll likely encounter an error related to NotificatorSpecsComponents, right? That’s because we haven’t created it yet. Let’s go ahead and do that first:</p><p><em>(Add this in the same file as the NotificatorSpecs protocol)</em></p><pre>public class NotificatorSpecsComponents {<br>    private (set) var observers: [NotificatorNameType: NSObject] = [:]<br>    fileprivate let observerChangeQueue: DispatchQueue<br>    <br>    init(observerChangeQueue: DispatchQueue = DispatchQueue.main) {<br>        self.observerChangeQueue = observerChangeQueue<br>    }<br>    <br>    fileprivate func changeObservers(type: NotificatorNameType,<br>                                     observer: NSObject) {<br>        observerChangeQueue.async {<br>            self.observers[type] = observer<br>        }<br>    }<br>    <br>    fileprivate func deleteObserver(type: NotificatorNameType) {<br>        observerChangeQueue.async {<br>            self.observers.removeValue(forKey: type)<br>        }<br>    }<br>}</pre><p>As you can see above, we’re using a class to store all the NotificationCenter observers used by an object. The main purpose of this class is to keep all active observers within the observers variable. Then, we have observerChangeQueue to manage any changes to the observers variable, ensuring that data races don’t occur when updates happen asynchronously.</p><p>Beyond that, this class also serves another important purpose: it restricts other developers from recklessly altering the observers data without going through the functions defined in our protocol 😡.</p><h3>Creating the NotificatorNameType Enum</h3><p>There’s one more thing we need to complete so our code can run smoothly: the NotificatorNameType enum! Naturally, we want our code to be as clean as possible when working with NotificationCenter, and that means we should avoid using raw strings throughout our app.</p><pre>public enum NotificatorNameType {<br>    case darkMode<br>    case whiteMode<br>    case blueMode<br>    case yellowMode<br>    case greenMode<br>    <br>    var name: Notification.Name {<br>        switch self {<br>        case .darkMode:<br>            return .init(rawValue: &quot;dark_mode_notification&quot;)<br>        case .whiteMode:<br>            return .init(rawValue: &quot;white_mode_notification&quot;)<br>        case .blueMode:<br>            return .init(rawValue: &quot;blue_mode_notification&quot;)<br>        case .yellowMode:<br>            return .init(rawValue: &quot;yellow_mode_notification&quot;)<br>        case .greenMode:<br>            return .init(rawValue: &quot;green_mode_notification&quot;)<br>        }<br>    }<br>}</pre><p>Feel free to use the case names that suit your needs best. The names I’ve provided above will be used to create a demo app, so no worries if you don’t follow them exactly.</p><p>We’re just one step away from reaching our main goal. The next step is to create an object class.</p><h3>Creating the Helper Class</h3><p>Of course, we can’t rely solely on the protocol; we need a class that will serve as the object to execute the functions defined in our protocol’s extension.</p><pre>import Foundation<br><br>public class NotificatorHelper: NotificatorSpecs {<br>    public let components: NotificatorSpecsComponents = NotificatorSpecsComponents()<br>    <br>    public init() { }<br>    <br>    deinit {<br>        print(&quot;\(self) is deinitialize&quot;)<br>    }<br>    <br>}</pre><p>When creating our helper class, as you can see, we don’t need to conform to the functions in our protocol in the usual way. By simply creating an empty class like the one above, we can access the functions with the same code inside it.</p><h3>Using Notificator 🤩</h3><p>We’ve finally reached the part we’ve all been waiting for: the real-world implementation in our program. Let’s dive in and integrate it into a simple app to showcase its benefits!</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br>    <br>    @IBOutlet weak var colorView: UIView!<br>    <br>    var notificator: NotificatorSpecs = NotificatorHelper()<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        notificator.observe(types: [<br>            .darkMode: (observer: self, completion: #selector(onDarkModeTriggered)),<br>            .blueMode: (observer: self, completion: #selector(onBlueModeTriggered)),<br>            .yellowMode: (observer: self, completion: #selector(onYellowModeTriggered)),<br>            .greenMode: (observer: self, completion: #selector(onGreenModeTriggered))<br>        ])<br>        <br>        mockTriggerNotification()<br>    }<br>    <br>    func mockTriggerNotification() {<br>        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {<br>            self.notificator.notify(type: .darkMode,<br>                                    object: nil,<br>                                    userInfo: nil)<br>        }<br>        <br>        DispatchQueue.main.asyncAfter(deadline: .now() + 5) {<br>            self.notificator.notify(type: .blueMode,<br>                                    object: nil,<br>                                    userInfo: nil)<br>        }<br>        <br>        DispatchQueue.main.asyncAfter(deadline: .now() + 7) {<br>            self.notificator.notify(type: .yellowMode,<br>                                    object: nil,<br>                                    userInfo: nil)<br>        }<br>        <br>        DispatchQueue.main.asyncAfter(deadline: .now() + 9) {<br>            self.notificator.notify(type: .greenMode,<br>                                    object: nil,<br>                                    userInfo: nil)<br>        }<br>    }<br>    <br>    @IBAction func onClickButton() {<br>        notificator.stopAllObserver()<br>        <br>        mockTriggerNotification()<br>    }<br>    <br>    @objc func onDarkModeTriggered() {<br>        colorView.backgroundColor = .black<br>    }<br>    <br>    @objc func onBlueModeTriggered() {<br>        colorView.backgroundColor = .blue<br>    }<br>    <br>    @objc func onYellowModeTriggered() {<br>        colorView.backgroundColor = .yellow<br>    }<br>    <br>    @objc func onGreenModeTriggered() {<br>        colorView.backgroundColor = .green<br>    }<br><br>}</pre><p>Here, I’ll provide an example showcasing how multiple notifications can be observed by our ViewController class. This is a common issue, as mentioned in the problem discussion earlier.</p><p>When you run the code, this is what you’ll see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*Yfd2RsRKTD98bWQpoHAhNw.gif" /><figcaption>Example of using NotificatorHelper</figcaption></figure><p>As you can see, it works well, right?</p><p>In the future, if you decide to stop using NotificationCenter or call stopAllObserver(), which in this app is represented by pressing the button below, the box should no longer change color. Give it a try, and you&#39;ll see that it behaves as expected.</p><h3>Testable Notifications</h3><p>With this implementation, we can now confidently test whether our NotificationCenter is successfully observing and executing its functions when notified by other notificators.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67NsKTsjbC2hJs02HSPPyg.png" /><figcaption>Success Run Test With NotificatorHelper</figcaption></figure><p>See? Isn’t it great to know that we can now test our NotificationCenter more accurately?</p><h3>Conclusion</h3><p>Using NotificationCenter has both positive and negative effects on our projects. As developers, we need to find ways to address these negative impacts. One effective approach is to consolidate all active notifications into a single list, which helps keep our code tidy and makes it easier for other developers to read and maintain in the future.</p><p>The solution presented in this article may have some limitations that I might have overlooked. For all the Swift developers out there reading this, I hope you find this useful for your projects. Remember, don’t just copy and paste the code — customize it to fit your project’s needs.</p><p>If you have any suggestions or feedback, feel free to drop them in the comments. After all, that’s what the comments section is for 😊</p><p>Happy coding, everyone!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a21a83704290" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/streamlining-notificationcenter-usage-in-swift-a21a83704290">Streamlining NotificationCenter Usage in Swift</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create Stunning Custom Animations for Your UIButton in Swift]]></title>
            <link>https://engineering.idn.media/animate-your-own-uibutton-in-swift-0c2b3d327d36?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/0c2b3d327d36</guid>
            <category><![CDATA[uibutton]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[animation]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 19:34:52 GMT</pubDate>
            <atom:updated>2024-07-24T19:37:02.881Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ul-aNzkx6V6DBiRf" /><figcaption>Photo by <a href="https://unsplash.com/@raypang?utm_source=medium&amp;utm_medium=referral">Raymond Pang</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Have you ever felt that the button animations in UIKit, especially UIButton in Swift, seem a bit dull? Sometimes, pressing a button in Android UI feels more satisfying and clearly indicates user interaction.</p><p>Adding touch effects to buttons or touchable views might seem trivial, but in reality, incorporating these effects can significantly enhance the user experience of our apps, making them more user-friendly and visually elegant. However, the built-in animation capabilities of UIButton are quite limited, typically involving a simple opacity change when pressed and released.</p><p>In this article, we will explore creating an animation effect for when a user presses a button, using a Ripple effect style that is commonly seen in many apps today.</p><h3>Creating Our Custom UIButton</h3><p>Firstly, we need to create our own subclass of UIButton so that we can override its existing functions. Let’s name our button “RippleButton.”</p><pre>import UIKit<br><br>class RippleButton: UIButton {<br><br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        setup()<br>    }<br><br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        setup()<br>    }<br><br>    private func setup() {<br>        // Do Something here<br>    }<br><br>}</pre><p>As usual, this is how we typically create a custom UI. Next, we need to create our own listener for when the user touches and releases the button. We’ll define this function within the RippleButton class at the appropriate location in the code.</p><pre>class RippleButton: UIButton {<br><br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        setup()<br>    }<br><br>    required init?(coder: NSCoder) {<br>        super.init(coder: coder)<br>        setup()<br>    }<br><br>    private func setup() {<br>        clipsToBounds = true<br>        addTarget(self, action: #selector(buttonTouchedUp(_:)), for: [.touchUpInside, .touchUpOutside])<br>    }<br>    <br>    override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>        super.touchesBegan(touches, with: event)<br>        <br>    }<br><br>    @objc private func buttonTouchedUp(_ sender: UIButton) {<br>        <br>    }<br>}</pre><p>As you can see, during the setup() function call, we set clipsToBounds to true for our RippleButton. This ensures that when we apply the Ripple animation, it stays within the bounds of our button.</p><p>Now, let’s move on to the most important part: the Ripple animation itself! We will create this using a CAShapeLayer that forms a circle, which will expand to fill our button.</p><pre>private var rippleLayer: CAShapeLayer?<br><br>private func createRippleEffect(at point: CGPoint) {<br>    // Calculate the radius for the ripple effect based on the largest dimension of the button<br>    let diameter = bounds.width * 2<br>    let path = UIBezierPath(ovalIn: CGRect(x: -diameter / 2, y: -diameter / 2, width: diameter, height: diameter))<br>    let rippleLayer = CAShapeLayer()<br>    rippleLayer.path = path.cgPath<br>    rippleLayer.position = point<br>    rippleLayer.fillColor = UIColor.black.cgColor<br>    rippleLayer.opacity = 0.2<br>    layer.addSublayer(rippleLayer)<br>    self.rippleLayer = rippleLayer<br><br>    let animation = CABasicAnimation(keyPath: “transform.scale”)<br>    animation.fromValue = 0.1<br>    animation.toValue = 1<br>    animation.duration = 0.5<br>    animation.delegate = self<br>    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)<br>    animation.isRemovedOnCompletion = true<br>    rippleLayer.add(animation, forKey: “rippleEffect”)<br>}</pre><p>The createRippleEffect() function creates a CAShapeLayer with a custom UIBezierPath, forming a perfect circle resembling water ripples. Utilizing CABasicAnimation() is ideal for scaling the circular rippleLayer, offering a cleaner approach compared to using standard UIView.animate() to transition from size (0, 0) to (diameter, diameter). Adjust the animation instance values as needed to achieve the desired speed.</p><p>It’s crucial to store the ripple layer in a global variable (rippleLayer) within our class. This allows us to manage its lifecycle effectively, which we&#39;ll discuss shortly.</p><p>Don’t forget to implement the CAAnimationDelegate protocol in our RippleButton class. This protocol informs us when the ripple animation completes, ensuring smooth interaction.</p><pre>extension RippleButton: CAAnimationDelegate {<br>  func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {<br>    // Do something<br>  }<br>}</pre><p>Remember the rippleLayer mentioned earlier? The reason we use a global variable to store this layer is because we&#39;ll eventually need to remove it. This becomes necessary when we want to stop or release the animation from the RippleButton, as illustrated in the following example code.</p><pre>private var isRefreshing = false<br><br>private func animateRemoveRippleLayer() {<br>    UIView.transition(with: self,<br>             duration: 0.3,<br>             options: [.allowUserInteraction, .transitionCrossDissolve]) {<br>      guard !self.isRefreshing else {<br>        self.isRefreshing = false<br>        return<br>      }<br>      self.rippleLayer?.removeFromSuperlayer()<br>      self.rippleLayer?.removeAllAnimations()<br>      self.rippleLayer = nil<br>      self.isRefreshing = false<br>    }<br>}</pre><p>Here, animateRemoveRippleLayer() serves the purpose of halting the animation whenever needed. To ensure smooth and user-friendly results, we apply animations using UIView.transition(). Don&#39;t worry about the isRefreshing variable yet; its role will become clearer as we progress through this article.</p><p>Now, let’s proceed to showcase the ripple animation when clicking our RippleButton. Upon evaluating the entire code, here is what we have:</p><pre>class RippleButton: UIButton {<br>  private var rippleLayer: CAShapeLayer?<br>  private var isRefreshing = false<br><br>  override init(frame: CGRect) {<br>    super.init(frame: frame)<br>    setup()<br>  }<br><br>  required init?(coder: NSCoder) {<br>    super.init(coder: coder)<br>    setup()<br>  }<br><br>  private func setup() {<br>    clipsToBounds = true<br>    addTarget(self, action: #selector(buttonTouchedUp(_:)), for: [.touchUpInside, .touchUpOutside])<br>  }<br><br>  override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>    super.touchesBegan(touches, with: event)<br><br>    // Get the location of the touch in the button’s coordinate system<br>    if let touch = touches.first {<br>      let location = touch.location(in: self)<br>      createRippleEffect(at: location)<br>    }<br>  }<br><br>  @objc private func buttonTouchedUp(_ sender: UIButton) {<br>    // Do Something<br>  }<br>  <br>  private func createRippleEffect(at point: CGPoint) {<br>    // Calculate the radius for the ripple effect based on the largest dimension of the button<br>    let diameter = bounds.width * 2<br>    let path = UIBezierPath(ovalIn: CGRect(x: -diameter / 2, y: -diameter / 2, width: diameter, height: diameter))<br>    let rippleLayer = CAShapeLayer()<br>    rippleLayer.path = path.cgPath<br>    rippleLayer.position = point<br>    rippleLayer.fillColor = UIColor.black.cgColor<br>    rippleLayer.opacity = 0.2<br>    layer.addSublayer(rippleLayer)<br>    self.rippleLayer = rippleLayer<br><br>    let animation = CABasicAnimation(keyPath: “transform.scale”)<br>    animation.fromValue = 0.1<br>    animation.toValue = 1<br>    animation.duration = 0.5<br>    animation.delegate = self<br>    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)<br>    animation.isRemovedOnCompletion = true<br>    rippleLayer.add(animation, forKey: “rippleEffect”)<br>  }<br><br>  private func animateRemoveRippleLayer() {<br>    UIView.transition(with: self,<br>             duration: 0.3,<br>             options: [.allowUserInteraction, .transitionCrossDissolve]) {<br>      guard !self.isRefreshing else {<br>        self.isRefreshing = false<br>        return<br>      }<br>      self.rippleLayer?.removeFromSuperlayer()<br>      self.rippleLayer?.removeAllAnimations()<br>      self.rippleLayer = nil<br>      self.isRefreshing = false<br>    }<br>  }<br>}<br><br>extension RippleButton: CAAnimationDelegate {<br>  func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {<br>    // Do something<br>  }<br>}</pre><p>Now, try running it and see the results!</p><p>Oops 😥, it seems it’s still not quite what we expected, right? The animation runs perfectly, but the rippleLayer remains stuck on the button and never disappears. This is why we need to call animateRemoveRippleLayer() to remove the layer when the animation completes or when the user releases their touch from the button.</p><pre>@objc private func buttonTouchedUp(_ sender: UIButton) {<br>    animateRemoveRippleLayer()<br>}<br><br>extension RippleButton: CAAnimationDelegate {<br>  func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {<br>    animateRemoveRippleLayer()<br>  }<br>}</pre><p>Voila! We’ve successfully removed the ripple layer from the button. However, there’s a new issue: the ripple animation only completes fully when we hold down the button. As soon as we release it, the animation stops abruptly, which creates a glitching effect — not quite what we want. We aim for the animation to flow smoothly like droplets falling into water, creating ripples around them. This is where we’ll utilize several variables to help us: isRefreshing, isTouching, and isHolding.</p><pre>import UIKit<br>class RippleButton: UIButton {<br>  private var rippleLayer: CAShapeLayer?<br>  private var isTouching = false<br>  private var isHolding = false<br>  private var isRefreshing = false<br><br>  override init(frame: CGRect) {<br>    super.init(frame: frame)<br>    setup()<br>  }<br><br>  required init?(coder: NSCoder) {<br>    super.init(coder: coder)<br>    setup()<br>  }<br><br>  private func setup() {<br>    clipsToBounds = true<br>    addTarget(self, action: #selector(buttonTouchedUp(_:)), for: [.touchUpInside, .touchUpOutside])<br>  }<br><br>  override func touchesBegan(_ touches: Set&lt;UITouch&gt;, with event: UIEvent?) {<br>    super.touchesBegan(touches, with: event)<br>    isTouching = true<br>    if rippleLayer != nil {<br>      rippleLayer?.removeFromSuperlayer()<br>      rippleLayer?.removeAllAnimations()<br>      rippleLayer = nil<br>      isRefreshing = true<br>    }<br>    // Get the location of the touch in the button’s coordinate system<br>    if let touch = touches.first {<br>      let location = touch.location(in: self)<br>      createRippleEffect(at: location)<br>    }<br>  }<br><br>  @objc private func buttonTouchedUp(_ sender: UIButton) {<br>    isTouching = false<br>    guard isHolding else {<br>      isHolding = false<br>      return<br>    }<br>    animateRemoveRippleLayer()<br>    isHolding = false<br>  }<br>  <br>  private func createRippleEffect(at point: CGPoint) {<br>    // Calculate the radius for the ripple effect based on the largest dimension of the button<br>    let diameter = bounds.width * 2<br>    let path = UIBezierPath(ovalIn: CGRect(x: -diameter / 2, y: -diameter / 2, width: diameter, height: diameter))<br>    let rippleLayer = CAShapeLayer()<br>    rippleLayer.path = path.cgPath<br>    rippleLayer.position = point<br>    rippleLayer.fillColor = UIColor.black.cgColor<br>    rippleLayer.opacity = 0.2<br>    layer.addSublayer(rippleLayer)<br>    self.rippleLayer = rippleLayer<br>    let animation = CABasicAnimation(keyPath: “transform.scale”)<br>    animation.fromValue = 0.1<br>    animation.toValue = 1<br>    animation.duration = 0.5<br>    animation.delegate = self<br>    animation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)<br>    animation.isRemovedOnCompletion = true<br>    rippleLayer.add(animation, forKey: “rippleEffect”)<br>  }<br><br>  private func animateRemoveRippleLayer() {<br>    UIView.transition(with: self,<br>             duration: 0.3,<br>             options: [.allowUserInteraction, .transitionCrossDissolve]) {<br>      guard !self.isRefreshing else {<br>        self.isRefreshing = false<br>        return<br>      }<br>      self.rippleLayer?.removeFromSuperlayer()<br>      self.rippleLayer?.removeAllAnimations()<br>      self.rippleLayer = nil<br>      self.isRefreshing = false<br>    }<br>  }<br>}<br><br>extension RippleButton: CAAnimationDelegate {<br>  func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {<br>    guard !isTouching else {<br>      isHolding = true<br>      return<br>    }<br>    animateRemoveRippleLayer()<br>    isHolding = false<br>  }<br>}</pre><p>Here, isTouching serves to limit animationDidStop() from executing its function prematurely. When the user holds down the button and then releases it, the buttonTouchedUp() function is triggered, which calls animateRemoveRippleLayer().</p><p>Next, isHolding detects whether the user is long-pressing the button and releasing it midway. If so, when the animation completes in animationDidStop(), we allow this function to call animateRemoveRippleLayer() to gracefully remove the ripple layer.</p><p>Lastly, isRefreshing comes into play when the user rapidly taps the button in quick succession, potentially causing animation glitches where the animation may not complete. To observe its impact, remove the isRefreshing code from our RippleButton file. Essentially, this variable informs the system that if the user presses the button too quickly and frequently, the animation needs to reset. During this reset, we ensure that the new ripple animation continues smoothly and completes without interruption (because UIView.transition() uses concurrency to execute animations, sometimes animation blocks continue to run for the new rippleLayer).</p><p>Now, run your app and see the results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*mjOkMVlcOiT8vUa0Wn-LOA.gif" /><figcaption>Expected Result</figcaption></figure><p>In conclusion, this simple example demonstrates how to create your own button with a custom animation. What’s intriguing is that you can develop your own design system for your app, enabling you to customize the RippleButton initializer in the future to modify attributes like color, ripple size, position, and more, which might not be achievable with third-party libraries.</p><p>I hope you found this article helpful! Happy Coding! See you in the next article 🚀</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0c2b3d327d36" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/animate-your-own-uibutton-in-swift-0c2b3d327d36">Create Stunning Custom Animations for Your UIButton in Swift</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How IDN’s iOS Team improve Clevertap implementations ]]></title>
            <link>https://engineering.idn.media/how-idns-ios-team-improve-clevertap-implementations-908be7d3cb9e?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/908be7d3cb9e</guid>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[clevertap]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Thu, 05 Oct 2023 06:55:14 GMT</pubDate>
            <atom:updated>2023-11-13T07:44:59.525Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_v5-oAPI4DWkVm1q.png" /></figure><p>Are you familiar with Clevertap? Clevertap is a company offering a range of customer engagement services, and one of the services that IDN utilizes is Remote Push Notification. In 2022, I embarked on the journey of integrating the Clevertap SDK into the IDN iOS application, and during this process, we encountered several critical issues that proved challenging to resolve with Clevertap’s support.</p><p>If you’re also using Clevertap’s services, this Medium post will delve into my team’s brief yet insightful experience in identifying these problems and uncovering practical solutions.</p><p>There are 3 major issues that we will discuss in this post</p><h3><strong>1. Implement Notification Service &amp; Notification Content <em>[TECHNICAL]</em> 💻</strong></h3><p>Okay… first thing first, we will talk about how developer SHOULD implement Notification Service &amp; Notification Content. I will not talk from the very first step, because it already explained correctly in <a href="https://developer.clevertap.com/docs/ios-quickstart-guide">Clevertap Docs</a>. The problem is, when you already implement everything in that documentation, you will see that you can’t push any of <strong>Rich Push Notification </strong>(Notification with image or carousel and etc). The solution is your info.plist in each of Notification Service and Notification Content! (PS: Don’t worry to co-paste these codes, it is not private and can be used publicly 😏)</p><p>Notification Service info.plist:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br> &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt;<br> &lt;string&gt;en&lt;/string&gt;<br> &lt;key&gt;CFBundleDisplayName&lt;/key&gt;<br> &lt;string&gt;NotificationService&lt;/string&gt;<br> &lt;key&gt;CFBundleExecutable&lt;/key&gt;<br> &lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br> &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br> &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt;<br> &lt;string&gt;6.0&lt;/string&gt;<br> &lt;key&gt;CFBundleName&lt;/key&gt;<br> &lt;string&gt;$(PRODUCT_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundlePackageType&lt;/key&gt;<br> &lt;string&gt;XPC!&lt;/string&gt;<br> &lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br> &lt;string&gt;1.0&lt;/string&gt;<br> &lt;key&gt;CFBundleVersion&lt;/key&gt;<br> &lt;string&gt;1&lt;/string&gt;<br> &lt;key&gt;NSExtension&lt;/key&gt;<br> &lt;dict&gt;<br>  &lt;key&gt;NSExtensionPointIdentifier&lt;/key&gt;<br>  &lt;string&gt;com.apple.usernotifications.service&lt;/string&gt;<br>  &lt;key&gt;NSExtensionPrincipalClass&lt;/key&gt;<br>  &lt;string&gt;CTNotificationServiceExtension&lt;/string&gt;<br> &lt;/dict&gt;<br> &lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br> &lt;dict&gt;<br>  &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt;<br>  &lt;true/&gt;<br> &lt;/dict&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;pl</pre><p>Notification Content info.plist:</p><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;<br>&lt;!DOCTYPE plist PUBLIC &quot;-//Apple//DTD PLIST 1.0//EN&quot; &quot;http://www.apple.com/DTDs/PropertyList-1.0.dtd&quot;&gt;<br>&lt;plist version=&quot;1.0&quot;&gt;<br>&lt;dict&gt;<br> &lt;key&gt;Allow Arbitrary Loads&lt;/key&gt;<br> &lt;true/&gt;<br> &lt;key&gt;Application Application App Transport Security Settings&lt;/key&gt;<br> &lt;dict/&gt;<br> &lt;key&gt;CFBundleDevelopmentRegion&lt;/key&gt;<br> &lt;string&gt;en&lt;/string&gt;<br> &lt;key&gt;CFBundleDisplayName&lt;/key&gt;<br> &lt;string&gt;NotificationContent&lt;/string&gt;<br> &lt;key&gt;CFBundleExecutable&lt;/key&gt;<br> &lt;string&gt;$(EXECUTABLE_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundleIdentifier&lt;/key&gt;<br> &lt;string&gt;$(PRODUCT_BUNDLE_IDENTIFIER)&lt;/string&gt;<br> &lt;key&gt;CFBundleInfoDictionaryVersion&lt;/key&gt;<br> &lt;string&gt;6.0&lt;/string&gt;<br> &lt;key&gt;CFBundleName&lt;/key&gt;<br> &lt;string&gt;$(PRODUCT_NAME)&lt;/string&gt;<br> &lt;key&gt;CFBundlePackageType&lt;/key&gt;<br> &lt;string&gt;XPC!&lt;/string&gt;<br> &lt;key&gt;CFBundleShortVersionString&lt;/key&gt;<br> &lt;string&gt;1.0&lt;/string&gt;<br> &lt;key&gt;CFBundleVersion&lt;/key&gt;<br> &lt;string&gt;1&lt;/string&gt;<br> &lt;key&gt;CleverTapAccountID&lt;/key&gt;<br> &lt;string&gt;&lt;/string&gt;<br> &lt;key&gt;CleverTapToken&lt;/key&gt;<br> &lt;string&gt;&lt;/string&gt;<br> &lt;key&gt;NSExtension&lt;/key&gt;<br> &lt;dict&gt;<br>  &lt;key&gt;NSExtensionAttributes&lt;/key&gt;<br>  &lt;dict&gt;<br>   &lt;key&gt;UNNotificationExtensionUserInteractionEnabled&lt;/key&gt;<br>   &lt;string&gt;1&lt;/string&gt;<br>   &lt;key&gt;UNNotificationExtensionCategory&lt;/key&gt;<br>   &lt;string&gt;CTNotification&lt;/string&gt;<br>   &lt;key&gt;UNNotificationExtensionDefaultContentHidden&lt;/key&gt;<br>   &lt;true/&gt;<br>   &lt;key&gt;UNNotificationExtensionInitialContentSizeRatio&lt;/key&gt;<br>   &lt;real&gt;0.1&lt;/real&gt;<br>   &lt;key&gt;UNNotificationExtensionUserInteractionEnabled&lt;/key&gt;<br>   &lt;true/&gt;<br>  &lt;/dict&gt;<br>  &lt;key&gt;NSExtensionMainStoryboard&lt;/key&gt;<br>  &lt;string&gt;MainInterface&lt;/string&gt;<br>  &lt;key&gt;NSExtensionPointIdentifier&lt;/key&gt;<br>  &lt;string&gt;com.apple.usernotifications.content-extension&lt;/string&gt;<br> &lt;/dict&gt;<br>&lt;/dict&gt;<br>&lt;/plist&gt;</pre><p><em>EXTRA CODE:</em></p><p>NotificationService.swift</p><pre>import CTNotificationService<br><br>class NotificationService: CTNotificationServiceExtension {<br><br>    var contentHandler: ((UNNotificationContent) -&gt; Void)?<br>    var bestAttemptContent: UNMutableNotificationContent?<br>    <br>    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -&gt; Void) {<br>        super.didReceive(request, withContentHandler: contentHandler)<br>    }<br><br>}</pre><p>NotificationViewController.swift</p><pre>import CTNotificationContent<br><br>class NotificationViewController: CTNotificationViewController {<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Do any required interface initialization here.<br>    }<br>    <br>    func didReceive(_ notification: UNNotification) {<br>        //<br>    }<br><br>}</pre><p>After you copy and paste that code to your project it will run smoothly <strong>ONLY FOR single image notification</strong> 😏 We are not done yet with other Rich Push Notification such as Carousel and etc.</p><h3><strong>2. Give “CTNotification” to Rich Media Category [PRODUCT] 🥸</strong></h3><p>To enable your Carousel and other rich media, you should add CTNotification to Rich Media Category in your <strong>Clevertap Dashboard</strong>. You can find it when you edit your push notification message before send push campaign id dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GLFpwMIymj2ZxLOBz3xVdA.png" /></figure><p>After that you can see that your notification will become Carousel notification when you <strong>hold click</strong> the notification.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*nReij5-aB-rYtPC7vodEvQ.png" /></figure><p>Horray! we already solved Single Image Notification and Carousel Image Notification! BUT WAIT, we still have new problem until this step, which is <strong>we can’t see the image preview </strong>when we send carousel image notification!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/317/1*4WgP5QVfZDv2gGY9EBFtxw.png" /></figure><p>It will be very difficult for users to find out that this notification can be long pressed to bring up our carousel, isn’t that right?🤔 Honestly, I just assumed this myself because I usually long press a notification if the notification has a preview image to the right 🫠.</p><h3>3. Notification Image Preview wont show in the Right Corner of the app [PRODUCT] 🥸</h3><p>Now, we will use Clevertap SDK itself to solve it’s SDK 😵‍💫. A bit confusing, but let me explain!</p><p>As you can see in the Clevertap Docs, it use it’s custom payload to load the notifications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*2uAKdBfSWeDpw_DfE0rJlg.png" /></figure><p>Can you see the <strong>ct_mediaType </strong>and <strong>ct_mediaUrl</strong>? YES! we will use those custom in app key to show media preview in our notification 🤭 Pretty smart, isn’t it?</p><p>In your Clevertap dashboard please do these steps:</p><ol><li>Navigate to <strong>Custom key-value pairs</strong> sections when editing your message</li><li>Add key <strong>ct_mediaUrl </strong>and <strong>ct_mediaType</strong> with your desired media to show just like the picture below<br><em>PS: Make sure to fill </em><strong><em>ct_mediaType </em></strong><em>extension exactly like your media file extension!</em></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*EXDKSXAECy0b-6OaE26LIw.png" /></figure><p>3. Send your push notification message!</p><p>Congratulations! we already solve most bugs in Clevertap SDK. Hope this post will help you guys to improve your clevertap implementation, and also if you have friend who work in Clevertap, you can pass this post to give insight to Clevertap Engineer Team…</p><p>God bless you All!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=908be7d3cb9e" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/how-idns-ios-team-improve-clevertap-implementations-908be7d3cb9e">How IDN’s iOS Team improve Clevertap implementations 📱</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get Photo “Exact” storage size in swift ]]></title>
            <link>https://engineering.idn.media/get-photo-exact-storage-size-in-swift-94bfef1e2afc?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/94bfef1e2afc</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[storage]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[memory-optimization]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 08:43:32 GMT</pubDate>
            <atom:updated>2023-07-07T07:47:59.913Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*cKPO5K5gr_qLylhm" /><figcaption>Photo by <a href="https://unsplash.com/@tosshio?utm_source=medium&amp;utm_medium=referral">Jatniel Tunon</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When developing iOS applications, it’s not uncommon for us to be separated from features that invite users to be able to upload an image through our iOS app. Including when I was developing an application that had this feature, I felt it was an easy feature and a solution could be found through searching by Google. Finally, I always use “<strong><em>data.count</em></strong>” code to calculate the size of the photo or image that the user wants to upload.</p><pre>extension UIImage {<br><br>    public enum DataUnits: String {<br>        case byte, kilobyte, megabyte, gigabyte<br>    }<br><br>    func getSizeIn(_ type: DataUnits)-&gt; String {<br><br>        guard let data = self.pngData() else {<br>            return &quot;&quot;<br>        }<br><br>        var size: Double = 0.0<br><br>        switch type {<br>        case .byte:<br>            size = Double(data.count)<br>        case .kilobyte:<br>            size = Double(data.count) / 1024<br>        case .megabyte:<br>            size = Double(data.count) / 1024 / 1024<br>        case .gigabyte:<br>            size = Double(data.count) / 1024 / 1024 / 1024<br>        }<br><br>        return String(format: &quot;%.2f&quot;, size)<br>    }<br>}</pre><p>Or get file from URL and get file size using FileManager:</p><pre>    guard let aStrUrl = Bundle.main.path(forResource: &quot;1&quot;, ofType: &quot;png&quot;) else { return }<br><br>   let aUrl = URL(fileURLWithPath: aStrUrl)<br>   print(&quot;Img size = \((Double(aUrl.fileSize) / 1000.00).rounded()) KB&quot;)<br><br>   extension URL {<br>        var attributes: [FileAttributeKey : Any]? {<br>            do {<br>                return try FileManager.default.attributesOfItem(atPath: path)<br>            } catch let error as NSError {<br>                print(&quot;FileAttribute error: \(error)&quot;)<br>            }<br>            return nil<br>        }<br><br>        var fileSize: UInt64 {<br>            return attributes?[.size] as? UInt64 ?? UInt64(0)<br>        }<br><br>        var fileSizeString: String {<br>            return ByteCountFormatter.string(fromByteCount: Int64(fileSize), countStyle: .file)<br>        }<br><br>        var creationDate: Date? {<br>            return attributes?[.creationDate] as? Date<br>        }<br>    }</pre><p>You can find those code publicly in StackOverflow, there are a lot of code similar like that.</p><p>I always use either of those code to calculate file size. Until one day when I uploaded an image using one of those codes, I found a calculation error from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/318/1*SKM6ObHHIeUgTB_RCozyhQ.png" /><figcaption>Image Example With Information Details</figcaption></figure><p>Just like the picture above, the storage size of the image is 2.8 MB. but when we use either of those codes, what appears in the output is 13 MB. The differences is too far 😮‍💨.</p><p>How did it happen? after I tried to read from various sources maybe it’s because each data / image read by our swift code is different from the image file that we see in detailed image information in the Photos application on our iPhone. <strong>it’s possible that the code is returning the actual file size, including any additional metadata or thumbnail images that may be embedded within the file.</strong></p><p>So that in the end there is only 1 way to reduce the size, namely by reducing the quality of our images 1 or more times so that the file becomes lighter. But this method is also less effective because the image quality can be worse than before and again we don’t know how much we have to reduce the image quality. How many times do we have to reduce the quality of an image? Does each image have to be reduced by 10 times? How can the file when downloaded by the user have low quality from the start and have a file size of only 500KB? Are we going to reduce the quality again? Wouldn’t that make the picture even less good looking?</p><p>This can be a “pain” for our users even though it looks like a trivial problem, because the user gets confused why the file he knows is only 5MB is said to be an error by our app which limits the user from uploading photos that are 10MB in size. So how can we solve this problem our iOS project?</p><h3><strong>The answer is using PHAsset! 😁</strong></h3><pre>import Photos<br>import Foundation<br><br>public extension PHAsset {<br>    /// Actual file size in local storage<br>    /// (precision level up to 2 decimal places)<br>    var fileSize: Float {<br>        let resource = PHAssetResource.assetResources(for: self)<br>        let imageSizeByte = resource.first?.value(forKey: &quot;fileSize&quot;) as? Float ?? 0.0<br>        let imageSizeMB = imageSizeByte / (1024.0 * 1024.0)<br>        let addAverageDeficit = imageSizeMB / 10<br>        // Calculate size with average size<br>        // ** {real_image_size} + {real_image_size + ({real_image_size} / 10})}<br>        // ** ----------------------------------------------------------------- **<br>        // **                                  2                                **<br>        return (imageSizeMB + (imageSizeMB + addAverageDeficit)) / 2<br>    }<br>}</pre><p>When you pick a photo using native iOS photo picker library, you can get it’s PHAsset from that image and calculate it using this code.</p><p>I already try it for a couple times, and it successfully created a <strong>exact</strong> file size that we see in Photos app.</p><p>From 22 Photos Data, there are 14 photos that succeeded to produce <strong>exact </strong>size like we see on Photo app. So actually that code is not perfect yet, but it’s calculation only missed about 0.01 MB for files that have size more than 1MB and 0.001 MB for files that have size that below 1MB. Example:<br>1. Expected Size = 1.3 MB — Calculated Size = 1.29 MB.<br>2. Expected Size = 0.540 MB — Calculated Size = 0.539 MB.</p><p>It still have possibility to miss, but it won’t that far if we use <strong><em>data.count</em></strong> code 🤣.</p><p>Hope It helps! God bless you!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=94bfef1e2afc" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/get-photo-exact-storage-size-in-swift-94bfef1e2afc">Get Photo “Exact” storage size in swift 🦅</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[iOS] Advanced Lottie Animation — Memory Management]]></title>
            <link>https://engineering.idn.media/ios-advanced-lottie-animation-memory-management-7016402f0b1a?source=rss-3a70217b11c0------2</link>
            <guid isPermaLink="false">https://medium.com/p/7016402f0b1a</guid>
            <category><![CDATA[lottie-animation]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Timotius Leonardo Lianoto]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 08:35:08 GMT</pubDate>
            <atom:updated>2023-07-07T07:44:33.934Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HRncAv0J9wYDIKDG" /></figure><h3>[iOS] Advanced Lottie Animation — Memory Management</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*gvjfjrL0bbD2EuawbyBXsA.png" /></figure><h3>What is Lottie? 🤔</h3><p>Lottie is a cross-platform library for <a href="https://github.com/airbnb/lottie-ios">iOS, macOS, tvOS</a>, <a href="https://github.com/airbnb/lottie-android">Android</a>, and <a href="https://github.com/airbnb/lottie-web">Web</a> that natively renders vector-based animations and art in realtime with minimal code.</p><p>Lottie loads and renders animations and vectors exported in the bodymovin JSON format. Bodymovin JSON can be created and exported from After Effects with <a href="https://github.com/bodymovin/bodymovin">bodymovin</a>, Sketch with <a href="https://github.com/buba447/Lottie-Sketch-Export">Lottie Sketch Export</a>, and from <a href="https://www.haiku.ai/">Haiku</a>.</p><p>We can use Lottie if we want to add an animation in our product in <strong>easy way</strong> because we don’t have to specify keyframe and setup core animation by ourself which may takes too much time 😄. Go to <a href="https://lottiefiles.com/">https://lottiefiles.com/</a> to create our Lottie files or search for existing Lottie files that already been created by other designer.</p><h3>Issue on Lottie 🚨</h3><p>When developing the livestreaming feature in the <a href="https://www.idn.app/">IDN App (by IDN Media)</a>, we included a “Gift” feature for users, which allows them to send animated gifts to the streamer. These animations are played on the screens of all viewers, including the streamer’s own device.</p><p>While implementing the “Gift” feature, we followed the instructions provided in the “ReadMe” file of the <a href="https://github.com/airbnb/lottie-ios">Lottie library repository</a>. However, upon closer examination of this livestreaming feature, we discovered that the memory usage never decreased after several instances of gift animations being played on the same ViewController!</p><pre>class FalseCodeViewController: UIViewController {<br>    <br>    var animation: LottieAnimationView?<br>    lazy var buttonPlay: UIButton = UIButton()<br>    let urlInString: String = &quot;https://assets9.lottiefiles.com/packages/lf20_1xU9Bzegk7.json&quot;<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        self.view.addSubview(buttonPlay)<br>        buttonPlay.translatesAutoresizingMaskIntoConstraints = false<br>        buttonPlay.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true<br>        buttonPlay.heightAnchor.constraint(equalToConstant: 100).isActive = true<br>        buttonPlay.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true<br>        buttonPlay.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true<br>        <br>        buttonPlay.setTitle(&quot;Play Animation&quot;, for: .normal)<br>        buttonPlay.setTitleColor(.blue, for: .normal)<br>        buttonPlay.titleLabel?.textAlignment = .center<br>        <br>        <br>        buttonPlay.addTarget(self, action: #selector(onButtonPlayTapped), for: .touchUpInside)<br>    }<br>    <br>    @objc func onButtonPlayTapped() {<br>        playRandomAnimation()<br>    }<br>    <br>    func playRandomAnimation() {<br>        let url = URL(string: urlInString)<br>        animation = LottieAnimationView(url: url!,<br>                                        closure: { _ in<br>            // Completions<br>        })<br>        <br>        animation?.animationLoaded = { animationView, animation in<br>            animationView.play { [weak self] _ in<br>                // Remove animation view from superview<br>                animationView.removeFromSuperview()<br>                self?.animation = nil<br>            }<br>        }<br>        <br>        guard let animation = animation else { return }<br>        <br>        self.view.addSubview(animation)<br>        view.layoutIfNeeded()<br>        animation.frame = self.view.frame<br>    }<br>}</pre><p>Above is a code snippet that I use to display a looping animation by pressing the “Play Animation” button. In the code snippet, I store a value called “<strong><em>animation</em></strong>” of type LottieAnimationView in a global variable within the <strong>FalseCodeViewController</strong> class. Every time the <em>animation.play({closure})</em> is executed in the playRandomAnimation() function, the animation will run. After the animation duration reaches its limit, we will call <em>removeFromSuperview()</em> on the <strong>“<em>animation</em>”</strong> variable and set it to nil.</p><p>According to the concept of memory management in iOS, the “<strong><em>animation</em></strong>” variable should no longer be holding any instances. However, the result is contrary to my expectations. Here is the video evidence:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FSRCsYbjL3Mw%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DSRCsYbjL3Mw&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FSRCsYbjL3Mw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/41c429b3702a637cb160def294530d00/href">https://medium.com/media/41c429b3702a637cb160def294530d00/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fcav9egJRW_k%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dcav9egJRW_k&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2Fcav9egJRW_k%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/569a5a96e4a498b5adc43bacc792aa1d/href">https://medium.com/media/569a5a96e4a498b5adc43bacc792aa1d/href</a></iframe><p>You can see from video 2.2 that the memory does not decrease even though we have removed the <strong>LottieAnimationView</strong> from the superview and set the value of the ‘<strong><em>animation</em></strong>’ variable to nil. I have even tried not making ‘<strong><em>animation</em></strong>’ a global variable inside the <strong>FalseCodeViewController</strong> class and only creating it when needed, as shown in the code below:</p><pre>func playRandomAnimation() {<br>        let url = URL(string: urlInString)<br>        let animation = LottieAnimationView(url: url!,<br>                                        closure: { _ in<br>            // Completions<br>        })<br>        <br>        animation.animationLoaded = { animationView, animation in<br>            animationView.play { [weak self] _ in<br>                // Remove animation view from superview<br>                animationView.removeFromSuperview()<br>                self?.animation = nil<br>            }<br>        }<br>        <br>//        guard let animation = animation else { return }<br>        <br>        self.view.addSubview(animation)<br>        view.layoutIfNeeded()<br>        animation.frame = self.view.frame<br>    }</pre><h3>How to Solve ✅</h3><p>After conducting some research and trying various things in this mock project, finally I and some friends from the IDN Media iOS team have found a solution to overcome this issue. The solution is to provide an additional UIView as a container for the <strong>LottieAnimationView</strong>.</p><pre>class AnimationContainerView: UIView {<br>    var animation: LottieAnimationView?<br>    <br>    func setupAnimation() {<br>        guard let animation = animation else { return }<br>        addSubview(animation)<br>        layoutIfNeeded()<br>        animation.frame = self.frame<br>    }<br>}</pre><pre>class TrueCodeViewController: UIViewController {<br>    <br>    // var animation: LottieAnimationView?<br>    var animationContainer: AnimationContainerView?<br>    lazy var buttonPlay: UIButton = UIButton()<br>    let urlInString: String = &quot;https://assets9.lottiefiles.com/packages/lf20_1xU9Bzegk7.json&quot;<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        view.backgroundColor = .lightGray<br>        <br>        self.view.addSubview(buttonPlay)<br>        buttonPlay.translatesAutoresizingMaskIntoConstraints = false<br>        buttonPlay.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true<br>        buttonPlay.heightAnchor.constraint(equalToConstant: 100).isActive = true<br>        buttonPlay.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true<br>        buttonPlay.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true<br>        <br>        buttonPlay.setTitle(&quot;Play Animation&quot;, for: .normal)<br>        buttonPlay.setTitleColor(.blue, for: .normal)<br>        buttonPlay.titleLabel?.textAlignment = .center<br>        <br>        buttonPlay.addTarget(self, action: #selector(onButtonPlayTapped), for: .touchUpInside)<br>    }<br>    <br>    @objc func onButtonPlayTapped() {<br>        playRandomAnimation()<br>    }<br>    <br>    func playRandomAnimation() {<br>        let url = URL(string: urlInString)<br>        animationContainer = AnimationContainerView()<br>        self.view.addSubview(animationContainer!)<br>        animationContainer?.frame = self.view.frame<br>        animationContainer?.animation = LottieAnimationView(url: url!,<br>                                        closure: { _ in<br>            // Completions<br>        })<br>        <br>        animationContainer?.animation?.animationLoaded = { animationView, animation in<br>            animationView.play { [weak self] _ in<br>                self?.animationContainer?.removeFromSuperview()<br>                self?.animationContainer = nil<br>            }<br>        }<br>        <br>        // guard let animation = animation else { return }<br>        <br>        // self.animationContainer?.addSubview(animation)<br>        // view.layoutIfNeeded()<br>        // animation.frame = self.animationContainer!.frame<br>        <br>         animationContainer?.setupAnimation()<br>    }<br>}</pre><p>In the code snippet above, we remove the variable ‘<strong><em>animation</em></strong>’ that previously held the <strong>LottieAnimationView</strong> and create a new variable called <strong>AnimationContainerView</strong>, which is defined outside the <strong>TrueCodeViewController</strong> class.</p><p>Similarly to the previous code in the <strong>FalseCodeViewController</strong>, after the animation finishes playing for its duration, we now remove the ‘<strong><em>animationContainer</em></strong>’ itself and also set it to nil.</p><p>⚠️ It’s important to note that we also create a new variable in the animationContainer called ‘<strong><em>animation</em></strong>’, which is a <strong>LottieAnimationView</strong>. The reference will be automatically lost when we remove and set nil to the ‘<strong><em>animationContainer</em></strong>’ variable.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2Fw2FDt9-xbDA%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3Dw2FDt9-xbDA&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cca05d4e08c58c0c5aab50dfc1f2e10e/href">https://medium.com/media/cca05d4e08c58c0c5aab50dfc1f2e10e/href</a></iframe><p>As seen in the video above, we can observe that memory decreases shortly after the Lottie animation has finished playing. This is beneficial for our app to avoid consuming excessive memory or even causing the app to force close during usage.</p><blockquote>It appears that the LottieAnimation is still present in memory. However, don’t worry, as this is caused by the Lottie SDK itself, which caches the LottieAnimation after downloading it. This caching allows the SDK to avoid re-downloading the animation when displaying it again in the future.</blockquote><blockquote>The purpose of this caching mechanism is to improve performance by reducing the need for network requests. The cached animation can be quickly accessed, resulting in a smoother user experience. However, please keep in mind that cached animations may consume additional memory.</blockquote><p>If you prefer not to create a separate UIView class like <strong>AnimationContainerView</strong> as shown in the given code example, you can simply create a regular UIView within the <strong>TrueCodeViewController</strong> and add the LottieAnimationView as a subview to that UIView. Here’s the code:</p><pre>class TrueCodeViewController: UIViewController {<br>    <br>    // var animation: LottieAnimationView?<br>    var animationContainer: UIView?<br>    lazy var buttonPlay: UIButton = UIButton()<br>    let urlInString: String = &quot;https://assets9.lottiefiles.com/packages/lf20_1xU9Bzegk7.json&quot;<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        view.backgroundColor = .lightGray<br>        <br>        self.view.addSubview(buttonPlay)<br>        buttonPlay.translatesAutoresizingMaskIntoConstraints = false<br>        buttonPlay.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true<br>        buttonPlay.heightAnchor.constraint(equalToConstant: 100).isActive = true<br>        buttonPlay.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true<br>        buttonPlay.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true<br>        <br>        buttonPlay.setTitle(&quot;Play Animation&quot;, for: .normal)<br>        buttonPlay.setTitleColor(.blue, for: .normal)<br>        buttonPlay.titleLabel?.textAlignment = .center<br>        <br>        buttonPlay.addTarget(self, action: #selector(onButtonPlayTapped), for: .touchUpInside)<br>    }<br>    <br>    @objc func onButtonPlayTapped() {<br>        playRandomAnimation()<br>    }<br>    <br>    func playRandomAnimation() {<br>        let url = URL(string: urlInString)<br>        animationContainer = UIView()<br>        self.view.addSubview(animationContainer!)<br>        animationContainer?.frame = self.view.frame<br>        let animation = LottieAnimationView(url: url!,<br>                                        closure: { _ in<br>            // Completions<br>        })<br>        <br>        animation.animationLoaded = { animationView, animation in<br>            animationView.play { [weak self] _ in<br>                self?.animationContainer?.removeFromSuperview()<br>                self?.animationContainer = nil<br>            }<br>        }<br>        <br>        // guard let animation = animation else { return }<br>        <br>         self.animationContainer?.addSubview(animation)<br>         view.layoutIfNeeded()<br>         animation.frame = self.animationContainer!.frame<br>        <br>//         animationContainer?.setupAnimation()<br>    }<br>}</pre><p>Either way is correct for me and will create the same output for our memory graph, we just need to determine which code is more suitable for us and our team, and adjust it to meet the needs of our project!</p><h3>Conclusion 👀</h3><p>Based on my experience, we can use the first approach, which is to store the LottieAnimationView variable in a class. However, there is a condition that the variable should only be used once, and after that, the ViewController with the animation should be dismissed. Additionally, I haven’t found any other workarounds unless the Lottie library owner fixes this issue.</p><p>Feel free to comment in the comment section if you have any feedback, questions, or objections. I apologize for any mistakes in this article, and I hope it can be helpful to you, Swift enthusiasts!</p><p>Last but not least, here is my repository that you can clone or etc if you want to try it by yourself.<br><a href="https://github.com/TimotiusLeonardo/LottieTrial">https://github.com/TimotiusLeonardo/LottieTrial</a></p><p>God bless you all!</p><blockquote>This article was created with the following resources version: <br>Xcode =&gt; 14.3 <br>Lottie-iOS =&gt; 4.2.0</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7016402f0b1a" width="1" height="1" alt=""><hr><p><a href="https://engineering.idn.media/ios-advanced-lottie-animation-memory-management-7016402f0b1a">[iOS] Advanced Lottie Animation — Memory Management</a> was originally published in <a href="https://engineering.idn.media/">IDN Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>