<?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 Akshat Sharma on Medium]]></title>
        <description><![CDATA[Stories by Akshat Sharma on Medium]]></description>
        <link>https://medium.com/@aks3800?source=rss-fc4083806af8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*_cbeEiU4r8UzHS7b.jpg</url>
            <title>Stories by Akshat Sharma on Medium</title>
            <link>https://medium.com/@aks3800?source=rss-fc4083806af8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 10:28:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aks3800/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[Creating and publishing a package]]></title>
            <link>https://medium.com/flutter-clan/creating-and-publishing-a-package-d58c177a95ee?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/d58c177a95ee</guid>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[badgecount]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 19:21:01 GMT</pubDate>
            <atom:updated>2021-07-01T07:15:06.167Z</atom:updated>
            <content:encoded><![CDATA[<h3>Creating and publishing a Flutter package</h3><p>If you are having a problem and you are able to solve it, it&#39;s highly likely that someone else also might have faced it or will face it in the future. In the programming universe, a problem can be anything whose solution is not straightforward. If a developer is able to figure out a way to solve the problem in a better manner, it should be shared with the community as well. <a href="https://flutter.dev/">Flutter</a> gives us a very simple tool to share our solutions globally. In this article, we’ll be exploring <a href="https://pub.dev/">pub.dev</a> and its wide use cases.</p><p>All Flutter developers make use of packages available at <a href="https://pub.dev/">pub.dev</a> in their applications. A package can be of two types, a Dart package or a Plugin package. A Dart package is a package that solves a problem in <a href="https://dart.dev/">Dart</a> language. It does not make use of any platform-specific APIs. Whereas a Plugin package is a package that uses both Dart and platform-specific APIs to make things work. In a Plugin package, <a href="https://dart.dev/">Dart</a> code communicates with native code written either in <a href="https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html#:~:text=Objective%2DC%20is%20the%20primary,capabilities%20and%20a%20dynamic%20runtime.">Objective C</a>, <a href="https://www.java.com/en/">Java</a>, <a href="https://developer.apple.com/swift/">Swift</a>, or <a href="https://kotlinlang.org/">Kotlin</a>.</p><p>For example, we had to fetch the current badge number on the App Icon in iOS. We learned the process to get it, in this <a href="https://link.medium.com/oCw6a9AZwhb">article</a>. So, if anyone else faces this use case, he/she can follow the steps and get it done. Or one can just import a package and straight away get the count using <a href="https://dart.dev/">Dart</a>. The latter sounds easy and less time-consuming. So let’s get into developing a package.</p><pre>flutter create --org com.aks --template=plugin --platforms=ios -i swift app_icon_badge</pre><p>Execute the above command in the terminal. Let’s break it down. We have given organization only to be used for a sample app that will be using the package. template specified can be either plugin or package. Platform if specified will tell which platform this plugin will support. Available platforms are: android, ios, web, linux, macos, and windows. For our use case, we will only make a plugin for ios. As you all know iOS development is done using swift or Objective C, we get a choice to use any one of these. Our <a href="https://dart.dev/">Dart</a> code will be communicating with either swift or Objective C whichever language we give after -i. The last parameter is the name of the package.</p><p>After executing the following command, <a href="https://flutter.dev/">Flutter</a> creates all the necessary files and gives us all the placeholders we require. The ease of development with <a href="https://flutter.dev/">Flutter</a> is mind-blowing. Openlib/app_icon_badge.dart. You’ll see a getter for fetching platformVersion. Let’s create our own getter function.</p><pre>static Future&lt;int&gt; get <em>count </em>async {<br>     final int badgeCount = await<br>                           <em>_channel</em>.invokeMethod(&#39;getBadgeCount&#39;);<br>     return badgeCount;<br>}</pre><p>Well, that’s it from the <a href="https://dart.dev/">Dart</a> side.</p><p>Now open ios/Classes/SwiftAppIconBadgePlugin.swift file. Please note, the name will differ as per your package name. In this file, you’ll find a function handle that gets invoked whenever we send a message from the <a href="https://dart.dev/">Dart</a> side. In this function, you can directly return the count like the following.</p><pre><strong>public</strong> <strong>func</strong> handle(<strong>_</strong> call: FlutterMethodCall, result: <strong>@escaping<br></strong>FlutterResult) {</pre><pre>    result(UIApplication.shared.applicationIconBadgeNumber)</pre><pre>}</pre><p>But this will return the same result even if we invoke a method with any name. Therefore as a best practice, we need to have a check for the method name.</p><pre>public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {<br>    switch call.method {<br>        case &quot;getBadgeCount&quot;:<br>           result(UIApplication.shared.applicationIconBadgeNumber)<br>        default:<br>           result(FlutterMethodNotImplemented)<br>    }<br>}</pre><p>This is it, now to fetch the current badge count all we need to do is this.</p><pre>final int result = await AppIconBadge.<em>count</em>;</pre><p>We are done creating a package, now let’s focus on getting it published.</p><p>First of all, push your code to <a href="https://github.com/">Github</a> in a public repository. As you are contributing this code to the community, this will be open source. One more benefit you can get out of this is that users might start contributing to your repository to serve their own purpose.</p><p>Open <a href="https://pub.dev/">pub.dev</a> and sign in using your Google account. This step is very crucial because while publishing the package, Flutter publisher will ask for authentication.</p><p>Make sure to add the description and usage inREADME.md file which will explain the functioning of the package on the face itself.</p><p>In pubspec.yaml file add the link of the repository for the key homepage. You can remove the authorkey as it is deprecated now.</p><p>Make sure to add LICENSE. A very easy solution to get the contents of LICENSE is from <a href="https://github.com/">GitHub</a> itself while creating a new repository.</p><p>In CHANGELOG.md file write down the current changes. Adding the date to the list also helps to understand the evolution of the package. For example.</p><pre>## [0.0.1] - 24th June 2021<br><br>* Added support for getting the current app icon badge count.</pre><p>That’s all we need to do.</p><p>Before publishing run the following command from the root of the project. It will help you figure out any issues remaining for successfully publishing your package.</p><pre>flutter pub publish --dry-run</pre><p>Finally, after resolving all issues you can run the final command.</p><pre>flutter pub publish</pre><p>After successful authentication, your package will be live for usage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*iCKZKoO4DuGNDBjCUCRWRA.png" /></figure><p>Until next time!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d58c177a95ee" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-clan/creating-and-publishing-a-package-d58c177a95ee">Creating and publishing a package</a> was originally published in <a href="https://medium.com/flutter-clan">Flutter Clan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Invoking native iOS code from Flutter]]></title>
            <link>https://medium.com/flutter-clan/invoking-native-ios-code-from-flutter-cabcfd46a30f?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cabcfd46a30f</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[method-channel]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 19:09:27 GMT</pubDate>
            <atom:updated>2021-07-01T07:12:29.362Z</atom:updated>
            <content:encoded><![CDATA[<h3>Invoking native iOS code from Flutter using MethodChannels</h3><p>During your <a href="https://flutter.dev/">Flutter</a> development, you might come across this situation when you’ll have to communicate with native platform APIs. If there is already a package on <a href="https://pub.dev/">pub.dev</a>, you just got lucky but if there is no package available you’ll have to get into this communication between Flutter and native code.</p><p><a href="https://flutter.dev/">Flutter</a> uses a very flexible system to call platform-specific APIs. In this article, we’ll be setting up a communication channel between Flutter and iOS code. We’ll be fetching the current badge count on the App Icon. On the native side, this can be done by the following one-liner.</p><pre>UIApplication.shared.applicationIconBadgeNumber</pre><p>Our native iOS app will keep listening to a message during the app’s lifecycle. From our futter app we will send a message on this channel. The native listener will now catch hold of this message and will return the response after verifying the message details.</p><p>Let’s begin! Make sure to check out the <a href="https://link.medium.com/U3Ahev1Ywhb">article</a> for setting up push notifications in flutter and the <a href="https://link.medium.com/99eaxH3Ywhb">article</a> for simulating push notifications on iOS simulators for playing around with badge counts.</p><p>In your widget let’s first create a channel for communication.</p><pre>static const platform = const MethodChannel(&#39;method_channel.flutter.dev/appIconBadge&#39;);</pre><p>The native and flutter sides of the channel are connected through a channel name passed in the constructor. For our example, we have given channel name method_channel.flutter.dev/appIconBadge.</p><p>Now we’ll be sending a message to the native side of the channel.</p><pre>final int result = await platform.invokeMethod(&#39;getBadgeCount&#39;);</pre><p>Now the name of the message getBadgeCount plays a very important role. If the native side has not implemented support for this message, the Flutter host will receive a PlatformExeption. Therefore it is advisable to use try-catch block while invoking to avoid crashes.</p><pre>String badgeCount;    <br>try {<br>      final int result = await platform.invokeMethod(&#39;getBadgeCount&#39;);<br>      badgeCount = &#39;Badge count: $result&#39;;<br>} on PlatformException catch (e) {<br>      badgeCount = &quot;Failed to get badge count: &#39;${e.message}&#39;.&quot;;    }</pre><p>Let’s get into the native side code. Open AppDelegate.swift file present inside ios/Runner path.</p><p>In <strong>didFinishLaunchingWithOptions</strong> method, we’ll be adding a listener for method_channel.flutter.dev/appIconBadge channel.</p><pre>let controller : FlutterViewController = window?.rootViewController as! FlutterViewController</pre><pre>let badgeChannel = FlutterMethodChannel(name: &quot;method_channel.flutter.dev/appIconBadge&quot;, binaryMessenger: controller.binaryMessenger)</pre><p>Now we’ll be adding the callback handler which will get executed whenever we callinvokeMethod from the flutter host.</p><pre>badgeChannel.setMethodCallHandler({ [weak self] (call: FlutterMethodCall, result: FlutterResult) -&gt; Void in<br>         // Note: this method is invoked on the UI thread.   <br>        guard call.method == &quot;getBadgeCount&quot; else { <br>           result(FlutterMethodNotImplemented)<br>           return<br>        }<br>        self?.receiveBadgeCount(result: result)<br>})</pre><p>Here we first check that the message if the name of the message isgetBageCount or not. If it is something else we will return FlutterMethodNotImplemented. Once we have guarded our check, we will execute the desired function.</p><pre>func receiveBadgeCount(result: FlutterResult) -&gt; Void {  <br>      result(UIApplication.shared.applicationIconBadgeNumber)<br>}</pre><p>Once you’ll run your application, your flutter app and the native app will be communicating successfully.</p><p>You can find the code on <a href="https://github.com/aks3800/FlutterIosMethodChannel">Github</a>. To test out different badge counts change the badge count in SamplePush.apns file and drag-drop it on the simulator. To learn about its functioning check out this article.</p><p>Here is a sneak peek.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*lRwRJyZcAJ25wdDvuqs7UQ.gif" /></figure><p>Having done this, check out the <a href="https://link.medium.com/g58m5phZwhb">article</a> to publish a package based on the above-implemented functionality so that others can also use it.</p><p>Happy Coding!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cabcfd46a30f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-clan/invoking-native-ios-code-from-flutter-cabcfd46a30f">Invoking native iOS code from Flutter</a> was originally published in <a href="https://medium.com/flutter-clan">Flutter Clan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simulating Push Notifications in iOS Simulator]]></title>
            <link>https://medium.com/flutter-clan/simulating-push-notifications-in-ios-simulator-ef222ec5b0cc?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef222ec5b0cc</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-simulator]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 17:51:48 GMT</pubDate>
            <atom:updated>2021-07-01T07:04:10.675Z</atom:updated>
            <content:encoded><![CDATA[<h3>Simulating Push Notifications on iOS Simulator</h3><p>I asked my father to buy me a Mac in 2016 for getting into <a href="https://developer.apple.com/documentation/">iOS development</a>. After learning few basic concepts I came across <a href="https://developer.apple.com/documentation/usernotifications">Push Notifications</a> which required a real device to work with. In the span of 6 months, I asked my father again to buy me an iPhone which I got after few disagreements. Buying an iPhone to understand and implement <a href="https://developer.apple.com/documentation/usernotifications">push notifications</a> did make sense until 2020. But with the release of <a href="https://developer.apple.com/documentation/xcode-release-notes/xcode-11_4-release-notes#:~:text=bot.%20(59068222%2C%2058615215)-,Simulator,-New%20Features">Xcode 11.4</a>, Apple started supporting push notifications on simulators.</p><p>Yes, you heard it right, we can now simulate push notifications behavior on the iOS simulators. Let’s get into it.</p><p>If you are a <a href="https://flutter.dev/">Flutter</a> developer, go ahead and check out the <a href="https://link.medium.com/anig11gYwhb">article</a> for setting up push notifications in your flutter app. If you are done setting up, you can skip the next section.</p><p>Well if you don’t have any setup done, let’s get it done quickly.</p><h4>Create a new Xcode project for your iOS app.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BhZP4ak5epz38HvGqIpBHQ.png" /></figure><p>Select the appropriate team and name for your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BzWtsjANolx4f3Qqg7BNkg.png" /></figure><p>Complete the remaining steps in the process and run the app on your simulator. You’ll see nothing but a white screen.</p><p>Open your AppDelegate.swift file and add the following function in the end.</p><pre><strong>func</strong> requestPermission() -&gt; Void {</pre><pre><strong>let</strong> notificationsCenter = UNUserNotificationCenter.current()</pre><pre>notificationsCenter.requestAuthorization(options: [.alert, .sound, .badge]) { granted, error <strong>in</strong></pre><pre><strong>if</strong> <strong>let</strong> error = error {</pre><pre>print(&quot;error while requesting permission: \(error.localizedDescription)&quot;)</pre><pre>}</pre><pre><strong>if</strong> granted {</pre><pre>print(&quot;permission granted&quot;)</pre><pre>} <strong>else</strong> {</pre><pre>print(&quot;permission denied&quot;)</pre><pre>}</pre><pre>}</pre><pre>}</pre><p>Call this function inside your didFinishLaunchingWithOptions function.</p><pre><strong>func</strong> application(<strong>_</strong> application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: <strong>Any</strong>]?) -&gt; Bool {</pre><pre>// Override point for customization after application launch.</pre><pre>requestPermission()</pre><pre><strong>return</strong> <strong>true</strong></pre><pre>}</pre><p>That’s it! This is all you need to do as of now. Run the app and grant access for push notifications.</p><h4>Create a file with an extension .apns</h4><p>Paste the following contents into this newly created file.</p><pre>{</pre><pre>&quot;aps&quot;: {</pre><pre>&quot;alert&quot;: {</pre><pre>&quot;subtitle&quot;: &quot;Sample subtitle&quot;,</pre><pre>&quot;title&quot;: &quot;Sample title&quot;,</pre><pre>&quot;body&quot;: &quot;This is the sample body of the push notification.&quot;</pre><pre>},</pre><pre>&quot;sound&quot;: &quot;default&quot;,</pre><pre>&quot;category&quot;: &quot;FLUTTER_NOTIFICATION_CLICK&quot;,</pre><pre>&quot;badge&quot;: 1,</pre><pre>},</pre><pre>&quot;source&quot;: &quot;some_key&quot;,</pre><pre>&quot;metadata&quot;: {</pre><pre>&quot;type&quot;: &quot;waiting_room&quot;,</pre><pre>},</pre><pre>&quot;click_action&quot;: &quot;FLUTTER_NOTIFICATION_CLICK&quot;,</pre><pre>&quot;Simulator Target Bundle&quot;: &quot;com.aks.pushApp&quot;,</pre><pre>}</pre><p>Make sure you use your app’s bundle identifier in Simulator Target Bundle .</p><p>Now all you need to do is drag .apns file onto your simulator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*G690697b1tDLO-Ok486mng.png" /></figure><p>You’ll see the magic!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-fDm3WvNdj6AEOTnzhtiBQ.png" /></figure><p>A small demo of working:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DNm9plFOmIDRfrlRWST97A.gif" /></figure><p>In the next <a href="https://link.medium.com/WhtkJLKYwhb">article</a> let’s make use of the above functionality for invoking iOS code from flutter.</p><p>Cheers!! Until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef222ec5b0cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-clan/simulating-push-notifications-in-ios-simulator-ef222ec5b0cc">Simulating Push Notifications in iOS Simulator</a> was originally published in <a href="https://medium.com/flutter-clan">Flutter Clan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Push Notifications in Flutter — 1]]></title>
            <link>https://medium.com/flutter-clan/push-notifications-in-flutter-1-59c7f0570137?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/59c7f0570137</guid>
            <category><![CDATA[notifications]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[firebase-messaging]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[push-notification]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Wed, 30 Jun 2021 17:44:01 GMT</pubDate>
            <atom:updated>2021-07-01T06:54:32.767Z</atom:updated>
            <content:encoded><![CDATA[<h3>Push Notifications in Flutter — 1</h3><p>Push Notifications are an integral part of any application. It helps to alert users to the information which they have opted-in from the app and services. For push notifications, <a href="https://flutter.dev/">Flutter</a> has an amazing companion in form of <a href="https://firebase.google.com/">Firebase</a>. I’ll be releasing a series of articles that will help you integrate this framework into your Flutter apps. In this article, we will do a general setup for our flutter app.</p><p>Let’s begin!</p><h4>Create a new flutter project</h4><pre>flutter create --org com.aks your_app</pre><p>To link our application with <a href="https://firebase.google.com/">firebase</a> we’ll have to add <a href="https://pub.dev/packages/firebase_core">firebase_core</a>. In your <em>pubspec.yaml</em> file add the following dependency.</p><pre>firebase_core: ^1.3.0</pre><p>Now go ahead and run the project. You’ll see the counter project up and running.</p><h4>Setup Firebase Project</h4><p>Create a new project on the <a href="https://console.firebase.google.com/">firebase console</a>.</p><p>Let’s first add an android app to this newly created firebase project. Copy your package identifier from android/app/src/main/AndroidManifest.xmlfile. Paste the copied identifier while registering a new Android app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PzpIE3vk47DYRsF1IP9RVg.png" /></figure><p>After registering the app, download the <em>google-services.json</em> file at the same level as your app’s <em>build.gradle</em> file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hlDgI5vKTy4_A4vwYDbe-w.png" /></figure><p>Now make the necessary changes to your project’s <em>build.gradle</em> file and to your app’s <em>build.gradle </em>file as described in the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xodHWxIoC11LMVoLKZSjlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FxmZKXTpkRv3xF8X9SoLLA.png" /></figure><p>Now let’s add a new iOS project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eZH6Ybmeu3fOkomc5ur-7w.png" /></figure><p>After registering the newly created iOS app, download <em>GoogleService-Info.plist</em> at the same level as your <em>info.plist</em> file under Runner folder and add it to your project.</p><p>We do not need to make any changes on the native side for firebase to work, that will be handled by <a href="https://pub.dev/packages/firebase_core">firebase_core</a> dependency which we earlier added.</p><p>In your <em>main.dart</em> file add the following lines to initialize the flutter app.</p><pre>WidgetsFlutterBinding.<em>ensureInitialized</em>();<br>await Firebase.<em>initializeApp</em>();</pre><h4>Add Firebase Messaging Package</h4><p><a href="https://pub.dev/packages/firebase_messaging">firebase_messaging</a> package gives us all the functionality out of the box which we need to make everything work. Add this dependency in your <em>pubspec.yaml</em> file and run your project once to download all the necessary files.</p><pre>firebase_messaging: ^10.0.2</pre><p>Make sure your iOS deployment target is 11 or higher to make things work. Uncomment the line in your Podfile and set the platform to 11.</p><pre>platform :ios, &#39;11.0&#39;</pre><h4>Adding Push Notifications capability</h4><p>Go to the Signing &amp; Capabilities section of your iOS app in Xcode and add <strong>Background Modes</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JHDqlWQTlY6O94OtQRZjmA.png" /></figure><p>Now checkmark <strong>Background fetch</strong> and <strong>Remote notifications</strong> option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ybzt23C2qxfy0KIN2X4NEQ.png" /></figure><p>All the project-specific steps are now done. Now we’ll be focussing on the dart side of code.</p><h3>Push Notifications Manager</h3><p>Firebase Messaging gives us few functions to work with for configuring the behavior of push notifications. Let’s create a class that will handle everything inside it. We want our manager only to be created once so that we can get the retrieved data from notifications everywhere. That means we’ll have to create a singleton class.</p><pre>class PushNotificationsManager {<br>  PushNotificationsManager._();<br><br>  factory PushNotificationsManager() =&gt; <em>_instance</em>;<br><br>  static final PushNotificationsManager <em>_instance </em>=    PushNotificationsManager._();<br>}</pre><p>Create a function to fetch the FCM token.</p><pre><em>/// Function to ask user for push notification permissions and if provided, save FCM Token in persisted local storage.<br></em>void _setFCMToken() async {<br>  FirebaseMessaging messaging = FirebaseMessaging.<em>instance</em>;<br><br>  <em>/// requesting permission for [alert], [badge] &amp; [sound]. Only for iOS<br>  </em>NotificationSettings settings = await messaging.requestPermission(<br>    alert: true,<br>    badge: true,<br>    sound: true,<br>  );<br><br>  <em>/// saving token only if user granted access.<br>  </em>if (settings.authorizationStatus == AuthorizationStatus.authorized) {<br>    String token = await messaging.getToken();<br>    print(&#39;FirebaseMessaging token: $token&#39;);<br>  }<br>}</pre><p>An app can receive notifications in any of the following app states: Foreground, Background, and Terminated State. The functionality of notifications can differ on basis of the state the app currently is in. Therefore we need to handle this in our scenario. Let&#39;s create an enum for this use case.</p><pre>enum AppState {<br>  foreground,<br>  background,<br>  terminated,<br>}</pre><p>Add a configure method to your manager to handle notifications tap behaviour.</p><pre><em>/// Function to configure the functionality of displaying and tapping on notifications.<br></em>void _configure() async {<br>  <em>/// For iOS only, setting values to show the notification when the app is in foreground state.<br>  </em>await FirebaseMessaging.<em>instance</em>.setForegroundNotificationPresentationOptions(<br>    alert: true,<br>    badge: true,<br>    sound: true,<br>  );<br><br>  <em>/// handler when notification arrives. This handler is executed only when notification arrives in foreground state.<br>  /// For iOS, OS handles the displaying of notification<br>  /// For Android, we push local notification<br>  </em>FirebaseMessaging.<em>onMessage</em>.listen((RemoteMessage message) {<br>    _showForegroundNotificationInAndroid(message);<br>  });<br><br>  <em>/// handler when user taps on the notification.<br>  /// For iOS, it gets executed when the app is in [foreground] / [background] state.<br>  /// For Android, it gets executed when the app is in [background] state.<br>  </em>FirebaseMessaging.<em>onMessageOpenedApp</em>.listen((RemoteMessage message) {<br>    _handleNotification(message: message.data, appState: AppState.foreground);<br>  });<br><br>  <em>/// If the app is launched from terminated state by tapping on a notification, [getInitialMessage] function will return the<br>  /// [RemoteMessage] only once.<br>  </em>RemoteMessage initialMessage = await FirebaseMessaging.<em>instance</em>.getInitialMessage();<br><br>  <em>/// if [RemoteMessage] is not null, this means that the app is launched from terminated state by tapping on the notification.<br>  </em>if (initialMessage != null) {<br>    _handleNotification(message: initialMessage.data, appState: AppState.terminated);<br>  }<br>}</pre><p>By default, on Apple devices notification messages are only shown when the application is in the background or terminated state. Calling the following method updates these options to allow customizing notification presentation behaviour whilst the application is in the foreground.</p><pre>await FirebaseMessaging.<em>instance</em>.setForegroundNotificationPresentationOptions(<br>  alert: true,<br>  badge: true,<br>  sound: true,<br>);</pre><p>To have the same functionality on Android we have to do some customization which we will cover in the subsequent series therefore we have left this function empty.</p><pre>void _showForegroundNotificationInAndroid(RemoteMessage message) async {}</pre><p>Function callbacks which gets triggered in the background and terminated state calls <em>_handleNotification</em> function in which we will handle the tap behaviour basis of the state the app currently is in.</p><pre>void _handleNotification({<br>  Map&lt;String, dynamic&gt; message,<br>  AppState appState,<br>}) async {<br>  print(&#39;PushNotificationsManager: _handleNotification ${message.toString()} ${appState.toString()}&#39;);<br>}</pre><p>In the end PushNotificationsManger will look like:</p><pre>import &#39;package:firebase_messaging/firebase_messaging.dart&#39;;<br><br>enum AppState {<br>  foreground,<br>  background,<br>  terminated,<br>}<br><br>class PushNotificationsManager {<br>  PushNotificationsManager._();<br><br>  factory PushNotificationsManager() =&gt; <em>_instance</em>;<br><br>  static final PushNotificationsManager <em>_instance </em>= PushNotificationsManager._();<br><br>  <em>/// Function to setup up push notifications and its configurations<br>  </em>Future&lt;void&gt; init() async {<br>    await _setFCMToken();<br>    _configure();<br>  }<br><br>  <em>/// Function to ask user for push notification permissions and if provided, save FCM Token in persisted local storage.<br>  </em>void _setFCMToken() async {<br>    FirebaseMessaging messaging = FirebaseMessaging.<em>instance</em>;<br><br>    <em>/// requesting permission for [alert], [badge] &amp; [sound]. Only for iOS<br>    </em>NotificationSettings settings = await messaging.requestPermission(<br>      alert: true,<br>      badge: true,<br>      sound: true,<br>    );<br><br>    <em>/// saving token only if user granted access.<br>    </em>if (settings.authorizationStatus == AuthorizationStatus.authorized) {<br>      String token = await messaging.getToken();<br>      print(&#39;FirebaseMessaging token: $token&#39;);<br>    }<br>  }<br><br>  <em>/// Function to configure the functionality of displaying and tapping on notifications.<br>  </em>void _configure() async {<br>    <em>/// For iOS only, setting values to show the notification when the app is in foreground state.<br>    </em>await FirebaseMessaging.<em>instance</em>.setForegroundNotificationPresentationOptions(<br>      alert: true,<br>      badge: true,<br>      sound: true,<br>    );<br><br>    <em>/// handler when notification arrives. This handler is executed only when notification arrives in foreground state.<br>    /// For iOS, OS handles the displaying of notification<br>    /// For Android, we push local notification<br>    </em>FirebaseMessaging.<em>onMessage</em>.listen((RemoteMessage message) {<br>      _showForegroundNotificationInAndroid(message);<br>    });<br><br>    <em>/// handler when user taps on the notification.<br>    /// For iOS, it gets executed when the app is in [foreground] / [background] state.<br>    /// For Android, it gets executed when the app is in [background] state.<br>    </em>FirebaseMessaging.<em>onMessageOpenedApp</em>.listen((RemoteMessage message) {<br>      _handleNotification(message: message.data, appState: AppState.foreground);<br>    });<br><br>    <em>/// If the app is launched from terminated state by tapping on a notification, [getInitialMessage] function will return the<br>    /// [RemoteMessage] only once.<br>    </em>RemoteMessage initialMessage = await FirebaseMessaging.<em>instance</em>.getInitialMessage();<br><br>    <em>/// if [RemoteMessage] is not null, this means that the app is launched from terminated state by tapping on the notification.<br>    </em>if (initialMessage != null) {<br>      _handleNotification(message: initialMessage.data, appState: AppState.terminated);<br>    }<br>  }<br><br>  void _showForegroundNotificationInAndroid(RemoteMessage message) async {}<br><br>  void _handleNotification({<br>    Map&lt;String, dynamic&gt; message,<br>    AppState appState,<br>  }) async {<br>    print(&#39;PushNotificationsManager: _handleNotification ${message.toString()} ${appState.toString()}&#39;);<br>  }<br>}</pre><p>Now call init method of your manager class in either Splash Screen or Home Page. For this project call this method in initState method of MyHomePage widget.</p><pre>@override<br>void initState() {<br>  PushNotificationsManager().init();<br>  super.initState();<br>}</pre><p>You can find the code <a href="https://github.com/aks3800/FlutterPushNotifications/tree/part1">here</a>. Make sure to check out the <a href="https://link.medium.com/ZcXsp12Xwhb">article</a> to test out push notifications on an iOS simulator.</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59c7f0570137" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-clan/push-notifications-in-flutter-1-59c7f0570137">Push Notifications in Flutter — 1</a> was originally published in <a href="https://medium.com/flutter-clan">Flutter Clan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a custom DartPad?]]></title>
            <link>https://medium.com/flutter-clan/how-to-create-a-custom-dartpad-b903939df94c?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b903939df94c</guid>
            <category><![CDATA[flutter-web]]></category>
            <category><![CDATA[dart]]></category>
            <category><![CDATA[dartlang]]></category>
            <category><![CDATA[dartpad]]></category>
            <category><![CDATA[flutter]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Fri, 04 Jun 2021 10:21:22 GMT</pubDate>
            <atom:updated>2021-06-04T10:21:22.031Z</atom:updated>
            <content:encoded><![CDATA[<p>We all love <a href="https://dartpad.dev/">DartPad</a>. As soon as you start your journey with <a href="https://flutter.dev/">Flutter</a>, you’ll come across this online editor to try out your dart ideas and solutions. I myself have tried numerous code snippets on DartPad whenever I felt too lazy to create a simple new Flutter project on my local and run it on a simulator or emulator.</p><p>It is truly amazing to use the power of Flutter on the web. That means I can write my code instantly on my tablet or even my mobile. But sadly as of today, we can only use core libraries while writing code in DartPad.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSu0GNMVYJuWuwOSW_aFew.png" /></figure><p>So this is the problem statement: <strong>We want to use different libraries on </strong><a href="https://pub.dev/"><strong>pub.dev</strong></a><strong> in DartPad.</strong></p><blockquote>According to me, understanding how to reach a solution is more important than knowing the solution. In this article, we will reach a solution so that while implementing you can improvise according to your needs.</blockquote><p>One second, if you are thinking that you’ll be needing prior knowledge of compiler design for this article, then mate you are absolutely wrong. All you need to know is <a href="https://dart.dev/">Dart</a>. 🤟🏻</p><p>Let’s go!!</p><p>Internally, DartPad uses <a href="https://github.com/dart-lang/dart-services">DartServices</a> to function. Creators of DartPad are using it for only UI purposes. They give an interface for an editor, the output, and few other configurations to run gist files. The code written in DartPad is sent to DartServices for compilation. <em>DartServices returns javascript back to DartPad</em> which gets rendered on the output panel using iFrame. This means that libraries requiring native mobile support won’t work in our case. Flutter web is the key here.</p><p>First, let’s set up our <a href="https://dartpad.dev/?null_safety=true">DartPad</a> and DartServices.</p><h3>Setting up your machine</h3><p>Download or clone the <a href="https://github.com/dart-lang/dart-pad">dart-pad</a> and <a href="https://github.com/dart-lang/dart-services">dart-service</a>.</p><p>Install NPM.</p><pre>brew install node</pre><p>Install <a href="https://www.npmjs.com/package/vulcanize">vulcanize</a>.</p><pre>npm install -g vulcanize</pre><p>I am pretty sure if you are reading this article, Flutter is already set up on your machine, if not then follow the instructions provided <a href="https://flutter.dev/docs/get-started/install">here</a>.</p><h4>Setting up local DartPad</h4><p>On the terminal, go to the downloaded or cloned folder of <a href="https://github.com/dart-lang/dart-pad">dart-pad</a> and run the following commands one by one.</p><pre>dart pub global activate grinder</pre><pre>dart pub get</pre><pre>grind serve</pre><p>Now hold on for some time. It takes a couple of minutes before the server is up and running. Once it is up, go to localhost:8000 run your first dart code on your local machine. Cheers!!🍻</p><p>Now open the network tab of your browser. You’ll see a couple of requests made like version, analyse, &amp; complile, etc. All of these requests are being made to DartServices. This means that the next step will be to point our local DartPad to our local DartServices server. To do this, go to build.yaml file present at the root level of your project and change the server URL to which you want your DartPad to point.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*luUjOr8zM40a8LSuqIpesQ.png" /><figcaption>Pointing dart-pad to local dart-services server</figcaption></figure><p>Again when you execute the following command,</p><pre>grind serve</pre><p>You’ll see that now your DartPad is making requests to 0.0.0.0:8082 which is not returning any response. You can use the custom port as per availability on your machine. Make sure to configure it while setting up the DartServices server.</p><h4>Setting up local DartServices server</h4><p>On the terminal, go to the downloaded or cloned folder of <a href="https://github.com/dart-lang/dart-services">dart-services</a> and run the following commands one by one.</p><pre>brew install protobuf (`brew upgrade protobuf` if already installer)</pre><pre>pub global activate grinder</pre><pre>pub global activate protoc_plugin</pre><pre>dart pub install</pre><pre>dart run tool/update_sdk.dart</pre><p>Before running the server, we’ll have to make sure on which address and port our server will be listening to. Go to lib/services_dev.dart and set 0.0.0.0 as server-url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GaaB6ezOdNqRJTs5XeltkA.png" /></figure><p>If you want your server to point to some other port then go to tool/grind.dart and change the port. By default, the port is set to 8082.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6uJQk-GJhnKXmjWT-eFWg.png" /></figure><p>[Optional] Just to be extra sure about the change print the server address.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I11a_Oxpl62mhx1ULf5aDA.png" /></figure><p>Now, go ahead and run</p><pre>grind serve</pre><p>You’ll see a lot of logs in your terminal and in that logs, you’ll find</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nYsHczNU4BooMpnaQZBIbg.png" /></figure><p>Cheers!! 🍻 Your DartServices server is up and running. Now your local DartPad which is pointing to the above-served server will run just like <a href="https://dartpad.dev/?null_safety=true">https://dartpad.dev/</a>.</p><h3>Adding support for pub.dev packages</h3><p>The above documentation is also available on <a href="https://github.com/dart-lang/dart-services/blob/master/README.md">Github</a>. The real game begins now.</p><h4>Stage 1</h4><p>Run the following code on your local DartPad</p><pre>import &#39;package:flutter/material.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Hello World&#39;,<br>      debugShowCheckedModeBanner: false,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: MyHomePage(),<br>    );<br>  }<br>}</pre><pre>class MyHomePage extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Hello World&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Container(<br>              width: 200,<br>              height: 200,<br>              color: Colors.red,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>The above code will give the following output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DnZU0rQZt3k7IoGY-1PWlA.png" /></figure><h4>Stage 2</h4><p>Now go ahead and add the dependency you want to use. In this example, we are going to use <a href="https://pub.dev/packages/dots_indicator">dots_indicator</a>.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:dots_indicator/dots_indicator.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Hello World&#39;,<br>      debugShowCheckedModeBanner: false,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: MyHomePage(),<br>    );<br>  }<br>}</pre><pre>class MyHomePage extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Hello World&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Container(<br>              width: 200,<br>              height: 200,<br>              color: Colors.red,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>Our DartServices does not understand what dots_indicator is hence it gives us an error that<em> target URI doesn’t exist</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MuOTsFfKDNbytjiH594rg.png" /></figure><p>Here is our first clue for our problem. We want our server to understand what we mean by dots_indicator. Now think that you are given some text which you need to understand, what will you do? You’ll start from the top and start understanding everything lines by line. Similarly, our server tries to understand each line. Creators of DartServices have limited the usage of external 3rd party dependencies. They simply find all the imports and check if the import belongs to the set of approved imports or not. If not then they straightaway give the error which we received. Until now dart compiler hasn’t come into the picture.</p><h4>Solution of the problem</h4><p>We need to find a way to bypass this security check. If you dig down the code of dart services you’ll find the list of pre-approved imports. Go to lib/src/project.dart. Here you’ll find a list of_flutterImportPrefixes. Add dots_indicator to the list as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/716/1*dWxHZ-6DN5wdzuALFJtcbg.png" /></figure><p>Now run the server again. And you’ll see a different error of Unsupported import which is returned by the flutter compiler.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LaPj92ZpLNUyDcdw-PPx4A.png" /></figure><h4>Stage 3</h4><p>Now the problem is that we need our server to understand all the capabilities of dots_indicator. Generally in our Flutter project, we do this by adding the dependency in pubspec.yaml file and once we run flutter pub get , all the dependencies are fetched and are ready to use.</p><h4>Solution of the problem</h4><p>If you read the logs when we run the server by command grind serve , it actually runs flutter pub get a couple of times in different directories, one of which is flutter_project. As soon as we run the project, Dart-Services creates a project with custom pubspec and run flutter pub get in that directory. Now the code written in the editor of DartPad is sent to DartServices which runs it as main.dart of this flutter_project.</p><p>Now go to file tool/grind.dart and function updateDependenciesFile and add dots_indicator to the list of dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*tleHHi6MIibwbr7BtSrFsA.png" /></figure><p>After making this change, run the server again using grind serve</p><p>Now our code won’t give an error. Anyways it will be giving a warning which is as expected that is Unused import.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Anl7hQaRSThDnTk6iquCag.png" /></figure><p>You can now start using dots_indicator</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:dots_indicator/dots_indicator.dart&#39;;</pre><pre>void main() {<br>  runApp(MyApp());<br>}</pre><pre>class MyApp extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return MaterialApp(<br>      title: &#39;Hello World&#39;,<br>      debugShowCheckedModeBanner: false,<br>      theme: ThemeData(<br>        primarySwatch: Colors.blue,<br>      ),<br>      home: MyHomePage(),<br>    );<br>  }<br>}</pre><pre>class MyHomePage extends StatelessWidget {<br>  <a href="http://twitter.com/override">@override</a><br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        title: Text(&#39;Hello World&#39;),<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: &lt;Widget&gt;[<br>            Container(<br>              width: 200,<br>              height: 200,<br>              color: Colors.red,<br>            ),<br>            DotsIndicator(<br>              dotsCount: 5,<br>              position: 1,<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>which will execute and give result as follows</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TrK6GWbWsPbLT1oSoeCIGQ.png" /></figure><p>Congratulations!</p><p>Using the above approach we can create our own DartPad supporting custom libraries from <a href="https://pub.dev/">pub.dev.</a> Happy coding! Until next time.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b903939df94c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/flutter-clan/how-to-create-a-custom-dartpad-b903939df94c">How to create a custom DartPad?</a> was originally published in <a href="https://medium.com/flutter-clan">Flutter Clan</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Advance Viper Architecture for iOS without Retain Cycles.]]></title>
            <link>https://medium.com/@aks3800/advance-viper-architecture-for-ios-without-retain-cycles-b1995a56903f?source=rss-fc4083806af8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1995a56903f</guid>
            <category><![CDATA[retain-cycle]]></category>
            <category><![CDATA[viper]]></category>
            <category><![CDATA[viper-architecture]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Akshat Sharma]]></dc:creator>
            <pubDate>Tue, 16 Apr 2019 14:41:27 GMT</pubDate>
            <atom:updated>2019-04-16T14:41:27.878Z</atom:updated>
            <content:encoded><![CDATA[<p>These days developers of big team give a lot of time in using and maintaining their code base with an Architecture which provides all the primes essentials of development cycle. As a developer it is very important to design our code so that each piece is easily identifiable, has specific and obvious purpose, and fits together with other pieces in a logical fashion.</p><p>In this article, I will introduce an approach to how to exactly use VIPER architecture in our iOS projects without falling under heaps and heaps of memory. This article is not a beginner for VIPER architecture but for those who have used it and might have struggled in identifying few memory issues.</p><p>Before continuing, kindly clone the project on <a href="https://github.com/aks3800/Viper_Architecture">GitHub</a>.</p><p>In this project, there are two view controllers which will very easily and clearly demonstrate the main issue. Home View Controller is the root view controller of the main navigation controller and account view controller pushed onto the Home VC.</p><p>After cloning the above mentioned repository, checkout “Without_VIPER” branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/542/1*02IN_UCrnYsYVBcXHTSZrg.png" /></figure><p>This branch shows the prime objective of this demo project. Two screens on one navigation stack. On pressing the Account button, Account VC gets pushed to the navigation controller. <br>On the console you’ll see that both view controllers are loaded into memory. Once you press the back button on navigation bar, you’ll see that the account view controller has been de-initialized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jxt2o3e1ABsB8ULVLndLpQ.png" /></figure><p>So, this is the base ground of our project. After popping the view controller, it should get de-initialized and memory should be freed.</p><p>Now checkout “Basic_VIPER” branch of the same repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/544/1*B2KNMYo7SNNZDs6UJ-TVwA.png" /></figure><p>Now both the view controllers are following the VIPER architecture methodology in the following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*1ANdxYXsoXn0whP3ijRW2A.png" /></figure><p>After running the application, you’ll see that on Home VC all the communications are being done. It is just simulating the basic flow of VIPER architecture. <br>On pressing the account button, Account VC will be pushed to navigation controller and a whole new chunk of objects will be added into memory. Now on pressing the back button, you’ll see that Account VC has not been de-initialized from memory.</p><p>Each time you press the account button on Home VC, you’ll keep adding bulk of objects into memory which will be holding reference to each other and will be retained.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*B4oC5_E-fhfm8tMlsn6yWw.png" /></figure><p>In a project like this with only two view controllers, if this memory management is not handled in a proper full fledged project, your application might be holding on to numerous dandling pointers.</p><p>Our task is to remove the above retain cycles.</p><p>Now checkout “Advance_VIPER” branch of the same repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*c_tzAZzNcUDQMJ0y8_ymhQ.png" /></figure><p>Our prime focus is on removing the above mentioned retain cycles from our project. There can be many ways to do the same, but I’ll be following the described approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*O9-qpZXSrunj5vL3Xq35bg.png" /></figure><p>I’ll be holding a weak reference of our V (View Controller) from our P (Presenter) and similarly will hold a weak reference of our P (Presenter) from our I (Interactor).</p><p>Presenter implementation will be in following way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ZU5loXPAoJ3JNp8Xe9l4Q.png" /></figure><p>When Account Presenter is de-initialized, we make our reference of interactor nil and as presenter — interactor reference is weak, there won’t be any retain cycle left. And Similarly for View and Presenter retain cycle will be handled.</p><p>Once you run the project and pop the Account VC, you’ll see that all the objects are now de-initialized from memory and memory is freed.</p><p>This article does not suggest the proper way of implementing VIPER architecture, it just shows that while implementing VIPER, iOS developers should take care of retain cycles in whichever way they find it easy. If these retain cycles are not handled, your application will suffer with memory issues, so better get on removing the same.</p><p>If you find any other more fascinating way to achieve the same, kindly share.</p><p><strong>Happy Coding!</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1995a56903f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>