<?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 Francesco Merola on Medium]]></title>
        <description><![CDATA[Stories by Francesco Merola on Medium]]></description>
        <link>https://medium.com/@francescomerola11?source=rss-34d2c453ee70------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*IIELp0ixnu_rKFP0WdEBFw.jpeg</url>
            <title>Stories by Francesco Merola on Medium</title>
            <link>https://medium.com/@francescomerola11?source=rss-34d2c453ee70------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 02:44:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@francescomerola11/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[iOS plugins integration into Flutter apps]]></title>
            <link>https://francescomerola11.medium.com/ios-plugins-integration-into-flutter-apps-c1984d742228?source=rss-34d2c453ee70------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1984d742228</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[plugin-development]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Francesco Merola]]></dc:creator>
            <pubDate>Sun, 22 Dec 2024 16:56:21 GMT</pubDate>
            <atom:updated>2024-12-22T16:56:21.406Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Apple logo" src="https://cdn-images-1.medium.com/max/1024/0*cRpebQb82lIuKuZG" /><figcaption>Photo by <a href="https://unsplash.com/@stm_2790?utm_source=medium&amp;utm_medium=referral">Sumudu Mohottige</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Flutter is an open-source UI toolkit developed by Google that allows developers to create natively compiled applications for mobile, web, and desktop from a single codebase. However, sometimes it is necessary to integrate iOS plugins to enlarge Flutter (and Dart, its programming language) development possibilities.</p><p>After a first setup we will proceed step by step, increasing the complexity and information quantity.</p><h4><strong>Prerequisites to follow this guide</strong></h4><p>Android Studio — Xcode — <a href="https://guides.cocoapods.org/using/getting-started.html">CocoaPods</a> — Flutter SDK — Dart SDK</p><h4>Reasons why</h4><p>iOS plugins for Flutter can be used for different reasons:</p><ul><li><strong>Accessing native iOS functionalities, </strong>that<strong> </strong>Dart code alone can’t reach. This includes APIs for camera, GPS and location services, push notifications and device sensors.</li><li><strong>Improving App Performance</strong>, especially for performance-intensive tasks, such as data encryption, image processing, or networking tasks.</li><li><strong>Integrating with iOS SDKs and Third-Party Libraries.</strong></li><li><strong>Maintaining a Native Feel, </strong>using native UI components to create a more iOS-native look and feel.</li><li><strong>Reducing Development Time, </strong>allowing developers to reuse native iOS code without fully rewriting functionalities in Dart.</li></ul><h4>Preliminary setup</h4><p>After this theoretical introduction, let’s work with Android Studio. At first, we have to create two projects: the Flutter app and the plugin. For convenience, I have created a folder named <strong><em>ios_plugin_example </em></strong>to store both projects in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QtZCFP_BaOzOhOWlIU2Ukg.png" /><figcaption>Android Studio — Flutter project configuration</figcaption></figure><p>The <strong>app</strong> can be simply created by generating a new Flutter project with Android Studio interface. At this point, clicking on the create button, you will see a basic project made up of<strong> ios folder </strong>(which contains the Runner.xcworkspace)<strong>, main.dart </strong>(which contains the entry point)<strong>, pubspec.yaml </strong>and other files.<br>Some insights on pubspec.yaml: it is an essential file in any Flutter project, used to manage dependencies, configure the project, and specify information like the app’s name, description, and version. It is located in the root of the project and acts as a “manifest” for the project.</p><p>Then, for the plugin setup we are going to use the terminal, digiting the following two commands:</p><ol><li><strong>flutter create — — template=plugin ios_example_plugin</strong><br>This will create a new configuration for a generic plugin that doesn’t support any platforms. In fact, once the command is run, the message “You’ve created a plugin project that doesn’t yet support any platforms” is displayed. Consider that you can replace “ios_example_plugin” with the actual name of your plugin.</li><li>To add the iOS platform, run <strong>flutter create -t plugin — — platforms=ios .</strong> under plugin folder.</li></ol><p>At this point, the plugin folder will contain all of these components that we are about to explore more in-depth:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_7drMvGU1TZ_ZHKD1owMFA.png" /><figcaption>iOS plugin components</figcaption></figure><p>Previous commands have also generated the <strong><em>example </em></strong>folder<strong><em>, </em></strong>which contains a Flutter app meant to link the plugin for testing it<strong><em>. </em></strong>We are not going to use it, but the app we have previously created.</p><h4>ios plugin folder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFyyM4LBFbt6rWKRtZUIBg.png" /></figure><p><strong>ios </strong>generally<strong> </strong>presents two other folders, Classes and Assets, that respectively contain the source code and the assets of the plugin, and a <strong>.podspec</strong> file, which is a specification file used in CocoaPods. It is written in <strong>Ruby </strong>and<strong> </strong>defines metadata about a library, enabling CocoaPods to understand how to download, build, and include it in a project. It generally includes some common properties; for our plugin we can set the following:</p><pre>Pod::Spec.new do |s|<br>  s.name             = &#39;ios_example_plugin&#39;<br>  s.version          = &#39;0.0.1&#39;<br>  s.summary          = &#39;A new Flutter plugin project.&#39;<br>  s.license          = { :file =&gt; &#39;../LICENSE&#39; }<br>  s.homepage         = &#39;http://example.com&#39;<br>  s.author           = { &#39;Your Company&#39; =&gt; &#39;email@example.com&#39; }<br>  s.source           = { :path =&gt; &#39;.&#39; }<br>  s.source_files = &#39;Classes/**/*&#39;<br>  s.resources = &#39;Assets/**/*&#39;<br>  s.platform = :ios, &#39;11.0&#39;<br><br>  s.dependency &#39;Flutter&#39;<br>  s.dependency &#39;Firebase&#39;<br><br>  # Flutter.framework does not contain a i386 slice.<br>  s.pod_target_xcconfig = { &#39;DEFINES_MODULE&#39; =&gt; &#39;YES&#39;, &#39;EXCLUDED_ARCHS[sdk=iphonesimulator*]&#39; =&gt; &#39;i386&#39; }<br>  s.swift_version = &#39;5.0&#39;<br>end</pre><p>In this way, we have specified different characteristics for our plugin, such as name, version, summary, license, homepage, author, dependencies (Flutter and Firebase), where the source code and assets are located (in our case, in Classes and Assets folder), platform, Swift version. If you want to know more about the syntax and all the possibilities, I suggest visiting the official CocoaPods <a href="https://guides.cocoapods.org/syntax/podspec.html">guide</a>.</p><p>In Classes folder there is an important class: IosExamplePlugin. It defines plugin registration to Flutter app (<strong>register</strong> method) and all the methods invoked by Flutter layer through the <strong>method channel</strong>.</p><pre>import Flutter<br>import UIKit<br><br>public class IosExamplePlugin: NSObject, FlutterPlugin {<br>  public static func register(with registrar: FlutterPluginRegistrar) {<br>    let channel = FlutterMethodChannel(name: &quot;ios_example_plugin&quot;, binaryMessenger: registrar.messenger())<br>    let instance = IosExamplePlugin()<br>    registrar.addMethodCallDelegate(instance, channel: channel)<br>  }<br><br>  public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {<br>    switch call.method {<br>    case &quot;getPlatformVersion&quot;:<br>      result(&quot;iOS &quot; + UIDevice.current.systemVersion)<br>    default:<br>      result(FlutterMethodNotImplemented)<br>    }<br>  }<br>}</pre><p>In particular,<strong> register</strong> method instantiates a named <strong>FlutterMethodChannel</strong>, which is responsible for the communication between Flutter and native layers, and sets this plugin class as a delegate to receive and manage dart calls toward <strong>native code</strong>. In fact, dart code can perform some methods that are implemented directly on that plugin class, specifically in <strong>handle</strong> function. These methods support a <strong>FlutterResult </strong>that Flutter layer will receive as a parameter after the execution. It can be also nil. In the code above there is an example method named “getPlatformVersion”, which returns the iOS version of the current device to the Flutter layer. These methods can use eventual <strong>parameters</strong> passed from the Flutter app; later we will see a complete example.</p><h4>lib plugin folder</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLy6bzet4m2ULOSjFNS5Sg.png" /><figcaption>lib plugin folder</figcaption></figure><p><strong>lib folder</strong> contains three main dart files that handle the interface for the communication between Flutter and the native layer.</p><p>1. <strong>plugin_name_platform_interface.dart</strong> file</p><pre>import &#39;package:plugin_platform_interface/plugin_platform_interface.dart&#39;;<br>import &#39;ios_example_plugin_method_channel.dart&#39;;<br><br>abstract class IosExamplePluginPlatform extends PlatformInterface {<br>  IosExamplePluginPlatform() : super(token: _token);<br><br>  static final Object _token = Object();<br><br>  static IosExamplePluginPlatform _instance = MethodChannelIosExamplePlugin();<br><br>  static IosExamplePluginPlatform get instance =&gt; _instance;<br><br>  static set instance(IosExamplePluginPlatform instance) {<br>    PlatformInterface.verifyToken(instance, _token);<br>    _instance = instance;<br>  }<br><br>  Future&lt;String?&gt; getPlatformVersion() {<br>    throw UnimplementedError(&#39;platformVersion() has not been implemented.&#39;);<br>  }<br>}</pre><p>The <strong>pluginNamePlatform</strong> class is an <strong>abstract platform interface</strong> designed to define the base interface for the plugin in Flutter. It leverages <strong>PlatformInterface</strong> (provided by the plugin_platform_interface package) and is used to support the <strong>Federated Plugin Architecture</strong>. This pattern allows for different platform-specific implementations (e.g., Android, iOS, Web) that share the same interface. When calling the constructor of the base class (PlatformInterface), a unique token (Object type) is provided. This token ensures that only authorized implementations can be registered as the instance. This instance is a singleton. The class defines the abstract methods that represent plugin functionalities.</p><p>2. <strong>plugin_name_method_channel.dart</strong> file</p><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class MethodChannelIosExamplePlugin extends IosExamplePluginPlatform {<br>  @visibleForTesting<br>  final methodChannel = const MethodChannel(&#39;ios_example_plugin&#39;);<br><br>@override<br>  Future&lt;String?&gt; getPlatformVersion() async {<br>    final version = await methodChannel.invokeMethod&lt;String&gt;(&#39;getPlatformVersion&#39;);<br>    return version;<br>  }<br>}</pre><p>The<strong> methodChannelPluginName </strong>class is the concrete one that extends <strong>pluginNamePlatform, </strong>so it defines the method channel and implements the interface methods.<strong> </strong>Method channel <strong>name</strong> must be the same as specified in the Swift plugin class; the same stands for method names.<br>In the code above, the first line of getPlatformVersion() calls the actual implementation of the method named <strong>“getPlatformVersion”</strong> defined in the Swift plugin class.</p><p>3. <strong>plugin_name_method_channel.dart</strong> file</p><p>This is the plugin class that exposes its methods, accessible directly from the Flutter app:</p><pre>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class IosExamplePlugin {<br>  Future&lt;String?&gt; getPlatformVersion() {<br>    return IosExamplePluginPlatform.instance.getPlatformVersion();<br>  }<br>}</pre><p>It has to be specified in <strong>pubspec.yaml</strong> file within the platform it is used for:</p><pre>name: ios_example_plugin<br>description: &quot;A new Flutter plugin project.&quot;<br>version: 0.0.1<br><br>environment:<br>  sdk: &#39;&gt;=3.2.6 &lt;4.0.0&#39;<br>  flutter: &#39;&gt;=3.3.0&#39;<br><br>dependencies:<br>  flutter:<br>    sdk: flutter<br>  plugin_platform_interface: ^2.0.2<br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^2.0.0<br><br>flutter:<br>  plugin:<br>    platforms:<br>      ios:<br>        pluginClass: IosExamplePlugin</pre><p>This entire structure makes the plugin:</p><ul><li><strong>Modular</strong>: each file has a clear responsibility.</li><li><strong>Scalable</strong>: you can add implementations for different platforms (e.g., Web, Desktop) without modifying the plugin core.</li><li><strong>Maintainable</strong>: by separating the interface, implementation, and communication, it becomes easier to test and update the plugin.</li></ul><h4>Linking</h4><p>Once the plugin is ready, the first action to perform is to link it as a Flutter app dependency. This time we have to modify<strong> the app pubspec.yaml:</strong></p><pre>name: example_flutter_app<br><br>description: &quot;A simple Flutter app to explain how iOS plugins work&quot;<br><br>publish_to: &#39;none&#39;<br><br>version: 1.0.0+1<br><br>environment:<br>  sdk: &#39;&gt;=3.2.6 &lt;4.0.0&#39;<br><br>dependencies:<br>  flutter:<br>    sdk: flutter<br>  cupertino_icons: ^1.0.2<br>  ios_example_plugin:<br>    path: ../ios_example_plugin<br>    # git:<br>    #  url: git@bitbucket.org:example/example.git<br>    #  ref: develop<br>    #  path: exampleFolder<br><br><br>dev_dependencies:<br>  flutter_test:<br>    sdk: flutter<br>  flutter_lints: ^2.0.0<br><br>flutter:<br>  uses-material-design: true</pre><p>In that way the <strong>relative path</strong> of the plugin source code to the app pubspec.yaml is specified. That path <strong>must</strong> contain plugin pubspec.yaml file and Plugin name (ios_example_plugin) <strong>must</strong> be the same as the one written in its pubspec.yaml. <br>Otherwise, it is also possible to include the plugin by giving information about its <strong>git</strong> reference with the following keywords:</p><ul><li><strong>url</strong></li><li><strong>ref</strong>, which is the name of the branch we want to consider</li><li><strong>path</strong>, where the plugin pubspec.yaml is located.</li></ul><p>We have explored the basic settings of our iOS plugin; let’s customize it a bit!</p><h4>Plugin customization</h4><p>Now we can enrich the plugin with a new method “showNativeScreen”, which shows a native screen and takes a string as a parameter. An update on the classes we have seen so far is necessary to do that.<br>This is how the various classes become with the addition of the new method:</p><pre>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class IosExamplePlugin {<br>  Future&lt;String?&gt; getPlatformVersion() {<br>    return IosExamplePluginPlatform.instance.getPlatformVersion();<br>  }<br><br>  Future&lt;String?&gt; showNativeScreen(String param) {<br>    return IosExamplePluginPlatform.instance.showNativeScreen(param);<br>  }<br>}</pre><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class MethodChannelIosExamplePlugin extends IosExamplePluginPlatform {<br>  @visibleForTesting<br>  final methodChannel = const MethodChannel(&#39;ios_example_plugin&#39;);<br><br>  @override<br>  Future&lt;String?&gt; getPlatformVersion() async {<br>    final version =<br>        await methodChannel.invokeMethod&lt;String&gt;(&#39;getPlatformVersion&#39;);<br>    return version;<br>  }<br><br>  @override<br>  Future&lt;String?&gt; showNativeScreen(String param) async {<br>    final string = await methodChannel.invokeMethod&lt;String&gt;(<br>        &#39;showNativeScreen&#39;, param);<br>    return string;<br>  }<br>}</pre><pre>import &#39;package:plugin_platform_interface/plugin_platform_interface.dart&#39;;<br>import &#39;ios_example_plugin_method_channel.dart&#39;;<br><br>abstract class IosExamplePluginPlatform extends PlatformInterface {<br>  IosExamplePluginPlatform() : super(token: _token);<br><br>  static final Object _token = Object();<br><br>  static IosExamplePluginPlatform _instance = MethodChannelIosExamplePlugin();<br><br>  static IosExamplePluginPlatform get instance =&gt; _instance;<br><br>  static set instance(IosExamplePluginPlatform instance) {<br>    PlatformInterface.verifyToken(instance, _token);<br>    _instance = instance;<br>  }<br><br>  Future&lt;String?&gt; getPlatformVersion() {<br>    throw UnimplementedError(&#39;platformVersion() has not been implemented.&#39;);<br>  }<br><br>  Future&lt;String?&gt; showNativeScreen(String param) {<br>    throw UnimplementedError(&#39;showNativeScreen() has not been implemented.&#39;);<br>  }<br>}</pre><pre>import Flutter<br>import UIKit<br>import FirebaseCore<br><br>public class IosExamplePlugin: NSObject, FlutterPlugin {<br>    public static func register(with registrar: FlutterPluginRegistrar) {<br>        let channel = FlutterMethodChannel(name: &quot;ios_example_plugin&quot;, binaryMessenger: registrar.messenger())<br>        let instance = IosExamplePlugin()<br>        registrar.addMethodCallDelegate(instance, channel: channel)<br>    }<br>    <br>    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {<br>        switch call.method {<br>        case &quot;getPlatformVersion&quot;:<br>            result(&quot;iOS &quot; + UIDevice.current.systemVersion)<br>            <br>        case &quot;showNativeScreen&quot;:<br>            guard let argument = call.arguments as? String, let vc = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController else {<br>                result(nil)<br>                return<br>            }<br>            <br>            let string = &quot;\(argument) \(FirebaseVersion())&quot;<br>            let vcToPresent = NativeScreenViewController(title: string)<br>            vc.present(vcToPresent, animated: true)<br>            result(nil)<br>            <br>        default:<br>            result(FlutterMethodNotImplemented)<br>        }<br>    }<br>}</pre><pre>import UIKit<br><br>class NativeScreenViewController: UIViewController {<br>    private var titleLabel: UILabel = {<br>        let label = UILabel()<br>        label.textColor = .black<br>        label.textAlignment = .center<br>        return label<br>    }()<br>    <br>    init(title: String) {<br>        super.init(nibName: nil, bundle: nil)<br>        titleLabel.text = title<br>    }<br><br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupUI()<br>    }<br>    <br>    private func setupUI() {<br>        view.backgroundColor = .red<br>        <br>        view.addSubview(titleLabel)<br><br>        titleLabel.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),<br>            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)<br>        ])<br>    }<br>}</pre><p><strong>NativeScreenViewController </strong>has to be added where all source files are supposed to be, i.e. in Classes folder (as specified in .podspec file).<br>The <strong>showNativeScreen</strong> method presents NativeScreenViewController on Flutter app entry point, which we can consider as our <strong>rootViewController</strong>.</p><p>For this article’s purpose the Flutter app is very simple, made up of the following main.dart file, which includes a button with the role to invoke the method exposed through the plugin class:</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:ios_example_plugin/ios_example_plugin.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      title: &#39;Flutter App Example&#39;,<br>      home: MyHomePage(),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatelessWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>        body: Center(<br>      child: ElevatedButton(<br>        style: ElevatedButton.styleFrom(<br>          backgroundColor: Colors.orange,<br>        ),<br>        onPressed: () async {<br>        await IosExamplePlugin()<br>              .showNativeScreen(&quot;Current version of Firebase:&quot;);<br>        },<br>        child: const Text(&quot;Click me&quot;, style: TextStyle(color: Colors.black)),<br>      ),<br>    ));<br>  }<br>}</pre><p>IosExamplePlugin.showNativeScreen(), as specified in the plugin interface, requires a String parameter. In general, you can pass any object you wish to the plugin, e.g. initialization parameters. With that method we have also leveraged Firebase, added as a dependency, intending to show its current version. Since in .podspec simply <strong>s.dependency ‘Firebase’</strong> is written, it signifies that the last version of it will be linked. If we would have wanted to use a specific version, we could have set it by digiting <strong>s.dependency ‘Firebase’, ‘xx.y.z’</strong>.</p><h4><strong>flutter pub get / pod install commands</strong></h4><p>For our aim we have to execute two powerful commands:</p><ol><li><strong>flutter pub get <br></strong>It is a Flutter-specific command that fetches all the dependencies listed in pubspec.yaml file. It downloads these packages from the <a href="https://pub.dev/"><strong>pub.dev</strong></a> repository (or any other source, such as a local or Git-based dependency) and places them into the <strong>.dart_tool</strong> directory of the Flutter project. It is important to use it every time a new package or dependency has been added in pubspec.yaml file.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kgpw61e8QxhrYPLSSDpHqg.png" /><figcaption>flutter pub get command</figcaption></figure><p><strong>Important</strong>: this command has to be executed in app <strong>root folder</strong>.</p><p>2.<strong> pod install<br></strong>It is a command from <strong>CocoaPods</strong>, a dependency manager for iOS and macOS projects. It resolves and installs iOS-specific native dependencies specified in a <strong>Podfile</strong>. Flutter uses CocoaPods to manage native iOS dependencies for plugins and system frameworks.<br>This command has to be executed when a new iOS plugin has been added, after flutter pub get has been called, after some Podfile changes and Flutter SDK updates. It also generates <strong>Runner.xcworkspace Pods target</strong>, which contains all app dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4pOXnFZBofZDNjP3bA00nA.png" /></figure><p><strong>Important</strong>: this command has to be executed in app <strong>ios folder</strong>.</p><p>You can digit previous commands in your sytem terminal or directly in Android Studio integrated one; and this will be the result:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*B9u0VINUzyFzYYuJbWRa8w.png" /></figure><p>You can work on the plugin directly through Pods target within the workspace in Xcode.</p><h4>Output</h4><p>Now let’s see the result of our work 😜<br>You can build and run the app with Android Studio or directly with Xcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mAtPpfJysHzN6PtlDpz__g.gif" /></figure><h4>Method channel bidirectionality</h4><p>Wait! We haven’t covered all method channel possibilities yet 😁.<br>Actually method channels permit a bidirectional communication between Flutter and native layer, so let’s see how to invoke dart functions from our plugin. In order to do this we have to set an handler that allows the method channel to listen and handle calls from native layer.<br>We can pass to the method channel (through a setup method) all the dart functions we want our plugin to invoke.</p><pre>import &#39;package:plugin_platform_interface/plugin_platform_interface.dart&#39;;<br>import &#39;ios_example_plugin_method_channel.dart&#39;;<br><br>abstract class IosExamplePluginPlatform extends PlatformInterface {<br>  IosExamplePluginPlatform() : super(token: _token);<br><br>  static final Object _token = Object();<br><br>  static IosExamplePluginPlatform _instance = MethodChannelIosExamplePlugin();<br><br>  static IosExamplePluginPlatform get instance =&gt; _instance;<br><br>  static set instance(IosExamplePluginPlatform instance) {<br>    PlatformInterface.verifyToken(instance, _token);<br>    _instance = instance;<br>  }<br><br>  Future&lt;String?&gt; showNativeScreen(String param) {<br>    throw UnimplementedError(&#39;showNativeScreen() has not been implemented.&#39;);<br>  }<br><br>  Future&lt;void&gt; setupPlugin(Function() executeSomeFlutterLogic) {<br>    throw UnimplementedError(&#39;setupPlugin() has not been implemented.&#39;);<br>  }<br>}</pre><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/services.dart&#39;;<br>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class MethodChannelIosExamplePlugin extends IosExamplePluginPlatform {<br>  @visibleForTesting<br>  final methodChannel = const MethodChannel(&#39;ios_example_plugin&#39;);<br><br>  late Function() executeSomeFlutterLogic;<br><br>  MethodChannelIosExamplePlugin() {<br>    methodChannel.setMethodCallHandler(_handleNativeCall);<br>  }<br><br>  Future&lt;dynamic&gt; _handleNativeCall(MethodCall call) async {<br>    switch (call.method) {<br>      case &#39;executeFlutterCode&#39;:<br>        return await executeSomeFlutterLogic();<br><br>      default:<br>        throw PlatformException(<br>          code: &#39;Unimplemented&#39;,<br>          details: &quot;The method &#39;${call.method}&#39; is not implemented.&quot;,<br>        );<br>    }<br>  }<br><br>  @override<br>  Future&lt;String?&gt; showNativeScreen(String param) async {<br>    final string =<br>        await methodChannel.invokeMethod&lt;String&gt;(&#39;showNativeScreen&#39;, param);<br>    return string;<br>  }<br><br>  @override<br>  Future&lt;void&gt; setupPlugin(Function() executeSomeFlutterLogic) async {<br>    this.executeSomeFlutterLogic = executeSomeFlutterLogic;<br>  }<br>}</pre><pre>import &#39;ios_example_plugin_platform_interface.dart&#39;;<br><br>class IosExamplePlugin {<br>  Future&lt;String?&gt; showNativeScreen(String param) {<br>    return IosExamplePluginPlatform.instance.showNativeScreen(param);<br>  }<br><br>  Future&lt;void&gt; setupPlugin(Function() executeSomeFlutterLogic) {<br>    return IosExamplePluginPlatform.instance.setupPlugin(executeSomeFlutterLogic);<br>  }<br>}</pre><p>Our handler is the method <strong>_handleNativeCall,</strong> set within method channel constructor. The class which defined it has now a new param: executeSomeFlutterLogic func, set through <strong>setupPlugin </strong>method, exposed by <strong>IosExamplePlugin</strong> class. For the communication from native to Flutter we have to use <strong>invokeMethod()</strong> on method channel.<br>The handler specifies that <strong>executeSomeFlutterLogic </strong>has to be called when invoked by native layer under<strong> </strong>“executeFlutterCode” name.</p><pre>import Flutter<br>import UIKit<br>import FirebaseCore<br><br>public class IosExamplePlugin: NSObject, FlutterPlugin {<br>    static private var methodChannel: FlutterMethodChannel?<br>    <br>    public static func register(with registrar: FlutterPluginRegistrar) {<br>        let channel = FlutterMethodChannel(name: &quot;ios_example_plugin&quot;, binaryMessenger: registrar.messenger())<br>        methodChannel = channel<br>        let instance = IosExamplePlugin()<br>        registrar.addMethodCallDelegate(instance, channel: channel)<br>    }<br>    <br>    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {<br>        switch call.method {<br>        case &quot;showNativeScreen&quot;:<br>            guard let argument = call.arguments as? String, let vc = UIApplication.shared.windows.first(where: { $0.isKeyWindow })?.rootViewController else {<br>                result(nil)<br>                return<br>            }<br>            <br>            let string = &quot;\(argument) \(FirebaseVersion())&quot;<br>            let vcToPresent = NativeScreenViewController(title: string)<br>            vc.present(vcToPresent, animated: true)<br>            result(nil)<br>            <br>        default:<br>            result(FlutterMethodNotImplemented)<br>        }<br>    }<br>    <br>    static func executeFlutterLogic() {<br>        methodChannel?.invokeMethod(&quot;executeFlutterCode&quot;, arguments: nil)<br>    }<br>}</pre><p>Compared to before, the method channel is now stored in a static private var: that’s why we will need to use it to invoke dart instructions (as happens in <strong>executeFlutterLogic()</strong> method).</p><p>Now we can intervene on NativeScreenViewController and main.dart file to set the communication between the two layers.</p><pre>import UIKit<br><br>class NativeScreenViewController: UIViewController {<br>    private var titleLabel: UILabel = {<br>        let label = UILabel()<br>        label.textColor = .black<br>        label.textAlignment = .center<br>        return label<br>    }()<br>    <br>    init(title: String) {<br>        super.init(nibName: nil, bundle: nil)<br>        titleLabel.text = title<br>    }<br><br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        setupUI()<br>    }<br>    <br>    override func viewDidDisappear(_ animated: Bool) {<br>        super.viewDidDisappear(animated)<br>        IosExamplePlugin.executeFlutterLogic()<br>    }<br>    <br>    private func setupUI() {<br>        view.backgroundColor = .red<br>        <br>        view.addSubview(titleLabel)<br><br>        titleLabel.translatesAutoresizingMaskIntoConstraints = false<br>        NSLayoutConstraint.activate([<br>            titleLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            titleLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>            titleLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 16),<br>            titleLabel.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -16)<br>        ])<br>    }<br>}</pre><pre>import &#39;package:flutter/foundation.dart&#39;;<br>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:ios_example_plugin/ios_example_plugin.dart&#39;;<br><br>void main() {<br>  runApp(const MyApp());<br>}<br><br>class MyApp extends StatelessWidget {<br>  const MyApp({super.key});<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return const MaterialApp(<br>      title: &#39;Flutter App Example&#39;,<br>      home: MyHomePage(),<br>    );<br>  }<br>}<br><br>class MyHomePage extends StatefulWidget {<br>  const MyHomePage({super.key});<br><br>  @override<br>  State&lt;MyHomePage&gt; createState() =&gt; _MyHomePageState();<br>}<br><br>class _MyHomePageState extends State&lt;MyHomePage&gt; {<br>  final plugin = IosExamplePlugin();<br><br>  int counter = 0;<br><br>  @override<br>  void initState() {<br>    super.initState();<br>    _initializePlugin();<br>  }<br><br>  Future&lt;void&gt; _initializePlugin() async {<br>    await plugin.setupPlugin(updateCounter);<br>    if (kDebugMode) {<br>      print(&quot;[log] Plugin initialized&quot;);<br>    }<br>  }<br><br>  void updateCounter() {<br>    setState(() {<br>      counter++;<br>    });<br>    if (kDebugMode) {<br>      print(&quot;[log] executeSomeFlutterLogic called. Counter: $counter&quot;);<br>    }<br>  }<br><br>  @override<br>  Widget build(BuildContext context) {<br>    return Scaffold(<br>      appBar: AppBar(<br>        backgroundColor: Colors.orange,<br>      ),<br>      body: Center(<br>        child: Column(<br>          mainAxisAlignment: MainAxisAlignment.center,<br>          children: [<br>            Text(<br>              &#39;Counter: $counter&#39;,<br>              style: const TextStyle(fontSize: 20),<br>            ),<br>            const SizedBox(height: 20),<br>            ElevatedButton(<br>              style: ElevatedButton.styleFrom(<br>                backgroundColor: Colors.orange,<br>              ),<br>              onPressed: () async {<br>                await plugin.showNativeScreen(&quot;Current version of Firebase:&quot;);<br>              },<br>              child: const Text(<br>                &quot;Click me&quot;,<br>                style: TextStyle(color: Colors.black),<br>              ),<br>            ),<br>          ],<br>        ),<br>      ),<br>    );<br>  }<br>}</pre><p>This basic example invokes <strong>updateCounter() </strong>dart method everytime the UIViewController is dismissed. It is passed to the plugin with <strong>setupPlugin</strong> method executed in the <strong>initState</strong>().</p><p>Our final product:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kn424MKbWS9PakAxbGwOyA.gif" /></figure><h4><strong>EventChannel</strong></h4><p>Despite the important role in this article, method channels are not the only way of communication between layers; also event channels can be used for that reason. Unlike a MethodChannel, which handles single requests and responses, <strong>EventChannel</strong> is designed for <strong>streaming data</strong>. This is useful when you want to send real-time updates or asynchronous events from the native code to Flutter, such as battery level changes, sensor updates, or location tracking.</p><h4>Personal notes</h4><p>I have decided to write this guide with the will to collect information about iOS plugin development, especially for those who, on their first approach, may encounter difficulties on the topic. The same theory can be applied also to big projects. My suggestion is to consult official documentation, especially related to Podfile and pubspec.yaml syntax if you want to know more and practise with complex settings.</p><p>Thanks for reading! I hope that this article has been useful for you. If you want, we can connect via LinkedIn: <a href="https://www.linkedin.com/in/francesco-merola-67654b245/"><em>Francesco.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1984d742228" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitFlow Guide]]></title>
            <link>https://francescomerola11.medium.com/gitflow-guide-b1bd02002fee?source=rss-34d2c453ee70------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1bd02002fee</guid>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[version-control]]></category>
            <category><![CDATA[gitflow]]></category>
            <category><![CDATA[git]]></category>
            <dc:creator><![CDATA[Francesco Merola]]></dc:creator>
            <pubDate>Fri, 08 Sep 2023 19:51:35 GMT</pubDate>
            <atom:updated>2023-09-08T19:51:35.116Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*GbBxuN2tQ5pt6_Xf" /><figcaption>Photo by <a href="https://unsplash.com/@synkevych?utm_source=medium&amp;utm_medium=referral">Roman Synkevych</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>GitFlow</strong> is a branching and workflow model for Git, one of the world’s most widely used version control systems. It was created by Vincent Driessen and is based on well-defined concepts to manage software development in an organized and collaborative manner. In this article I want to show you how to install and use it, confronting it with the original <strong>git commands</strong>. In addition, you need to know that GitFlow is a Git extension, so nothing will change in already existing repositories.</p><h4>Installing GitFlow on Mac</h4><p>My advice is to use <strong>brew</strong>, which is a very useful open source package manager. It allows you to install all common macOS packages, including <strong>git-flow</strong>. Before that, you can install brew on its website: <a href="https://brew.sh/">https://brew.sh</a>/. Furthermore, install the package with this command on the <strong>terminal</strong>:</p><pre>brew install git-flow</pre><h4>Installing GitFlow on Windows</h4><p>For Windows, git-flow is a part of the <strong>git installer</strong>. You can download it from <a href="https://git-scm.com/download/win">https://git-scm.com/download/win</a>.</p><h4>Installing GitFlow on Linux</h4><p>Probably the package is already installed on your machine. Otherwise, it is possible to have it from the system package manager. If you have Linux Fedora, CentOS or RedHat, use <strong>yum</strong>:</p><pre>yum install git-flow</pre><p>If you have a Debian or Ubuntu system instead, use<strong> apt-get</strong>:</p><pre>apt-get install git-flow</pre><h4>Master and develop branches</h4><p>The entire structure of GitFlow is centered around the concept of two branches: <strong>master</strong> and <strong>develop</strong>. ‘Master’ reflects the public release of the project that can be seen by the users, while ‘develop’ includes the implementation of the next versions and it is the base for future integrations. So, these two branches compose the <strong>skeleton</strong> of the project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zy2K7JtdjlS4iDXX2xwNNw.png" /><figcaption>GitFlow schema</figcaption></figure><p>If you are not using GitFlow, you have to create the develop branch from the main one with the original git commands:</p><pre>git branch develop<br>git push -u origin develop</pre><p>GitFlow provides us with commands that are the <strong>shortened form</strong> of one or more git ones. The first instruction to write on the terminal to use GitFlow is ‘git flow init’: it checks the existence of the master and develop branches and creates them automatically if not done before. The command generates different questions but we can avoid them by leaving default values:</p><pre>$ git flow init<br>Initialized empty Git repository in ~/project/.git/<br>No branches exist yet. Base branches must be created now.<br>Branch name for production releases: [master]<br>Branch name for &quot;next release&quot; development: [develop]<br>How to name your supporting branch prefixes?<br>Feature branches? [feature/]<br>Release branches? [release/]<br>Hotfix branches? [hotfix/]<br>Support branches? [support/]<br>Version tag prefix? []<br>$ git branch<br>* develop<br> master</pre><p>Remember to move to the project folder before digiting the command described above.</p><h4>Features control</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*mWbys9ZZF9FgUcVLWWBNJw.png" /><figcaption>Features flow</figcaption></figure><p>Each new feature should be associated with a <strong>new branch</strong>, created from the develop one. The new branch will be merged in the develop branch (never in the master) once the feature is complete. The first task can be accomplished with the common git commands:</p><pre>git checkout develop<br>git checkout -b feature/new_feature_name</pre><p>GitFlow condenses the two operations in one single command:</p><pre>git flow feature start new_feature_name</pre><p>The same treatment affects the new branch merge in develop. Let’s consider the comparison between Git and Gitflow:</p><pre>git checkout develop<br>git merge feature/new_feature_name</pre><pre>git flow feature finish feature/new_feature_name</pre><h4>Finalize a new release</h4><p>When the development branch has embedded enough features, a new <strong>release</strong> of the project can occur. To do this, we’ll create a new branch from the develop one, called <strong>release/x </strong>(x is a progressive release number), where it is possible to fix the last bugs, write documentation, clean or add comments (typical operations before a release). When the branch is ready, it will be merged into the master one and then in develop. This approach allows the developers to work on incompleted features while finalizing a release. In addition, it is necessary to provide a <strong>tag</strong> between master and release/x, that is the x number. Let’s see how to create a new release branch, always following the comparison between Git and GitFlow:</p><pre>git checkout develop<br>git checkout -b release/x</pre><pre>$ git flow release start x<br>Switched to a new branch &#39;release/x&#39;</pre><p>We can admire the synthesis power of GitFlow when releasing a new version of the project. With git commands:</p><pre>git checkout develop<br>git merge release/x<br>git checkout master<br>git merge release/x<br>git tag x<br>git branch -D release/x</pre><p>The last command deletes the branch.</p><p>With GitFlow:</p><pre>git flow release finish &#39;x&#39;</pre><p>No words needed.</p><h4>Create a hotfix</h4><p>GitFlow considers also <strong>another type of branch</strong>, called hotfix, that is used to <strong>fix bugs</strong> (0-day vulnerabilities, for instance) belonging to the current release. This kind of branch has a faster flow than the others, and since it proposes to fix already released bugs, it is created directly from the master. Once the problems are fixed the hotfix will be merged in both of the main branches of the project, or in the main and in the release branch, if exists. This approach allows developers to do bug fixing without interrupting the work on other branches. Here are the commands to create a hotfix branch:</p><pre>git checkout master<br>git checkout -b hotfix/bug_name</pre><pre>git flow hotfix start bug_name</pre><p>Commands to merge the completed branch and then delete it with the classic git approach:</p><pre>git checkout master<br>git merge hotfix/bug_name<br>git tag x.y<br>git checkout develop<br>git merge hotfix/bug_name<br>git branch -D hotfix/bug_name</pre><p>With GitFlow we need one single line:</p><pre>git flow hotfix finish bug_name</pre><p>As seen before, each commit or merge in the master will generate a new release number (x.y in the example above).</p><p>Thanks for reading! I hope that this article has been useful for you. If you want to talk or have a coffee, contact or connect to me via LinkedIn: <a href="https://www.linkedin.com/in/francesco-merola-67654b245/"><em>Francesco.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1bd02002fee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to make your app ready to use HomeKit]]></title>
            <link>https://francescomerola11.medium.com/how-to-make-your-app-ready-to-use-homekit-9e335d2ac53b?source=rss-34d2c453ee70------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e335d2ac53b</guid>
            <category><![CDATA[homekit]]></category>
            <dc:creator><![CDATA[Francesco Merola]]></dc:creator>
            <pubDate>Sun, 21 May 2023 09:08:14 GMT</pubDate>
            <atom:updated>2023-09-08T20:03:44.109Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*oAd3WjyjfMIcx-sob7cogg.jpeg" /></figure><p>With the advent of smart homes and connected devices, the ability to control and automate your home has become an increasingly accessible reality. Apple, with its <strong>HomeKit framework</strong>, has provided developers with a powerful tool to create apps that fully leverage the capabilities of HomeKit-compatible home devices. In this article we will explore how to set up your iOS app in Xcode to use HomeKit.</p><p>First of all, you must add the HomeKit capability to your project: this can be done in <strong><em>Signing &amp; Capability </em></strong>section in Xcode. After that, the following panel will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RZFlma4xrgF9sJMT83E2A.png" /></figure><p>As Xcode reminds you, it is possible to download <strong>HomeKit Simulator</strong>, a very useful tool that provides you with fictitious devices to test the app.</p><h4>HomeKit Accessory Simulator</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s4AOZXS4FOFBr86rgVsNTg.png" /></figure><p>The simulator is very simple to use: it allows devices to be added (with the plus button on the bottom left) and shows their properties. Keep in mind this recurrent fixed scheme for an HomeKit device: an accessory provides <strong>services</strong> and each service presents <strong>characteristics</strong>. In the previous image, a lightbulb was considered, called TestingLight. The service of interest is Lightbulb 71, which shows three characteristics: the state of the light, the brightness and the hue. If you want, you can add the characteristics you prefer. To add the simulated device to the Home app, provided directly by Apple, you need to scan the <strong>QR code</strong> (“setup code”).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*umC1gMFYcD9HKRWzUdKzUA.jpeg" /></figure><h4>Permission</h4><p>Before starting to develop, it’s necessary to give the possibility for the app to be granted permission from the user. The app has to access the devices information in order to leverage HomeKit. To do this, you need to add the <em>NSHomeKitUsageDescription </em>key in the <strong>Custom iOS Target Properties</strong> (in the Targets section of your app — info) and provide it with a description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CC1RqBVxoXsViHDfDRIPuA.png" /><figcaption>Look at the highlighted row</figcaption></figure><p>The first time the user opens the app, an alert will appear, showing the aim to have permission to use Home data. The user can manage the permission in iPhone settings whenever he wants.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mdoogVpqaitCOLOEN_wuCw.jpeg" /></figure><p>Excellent! After these preliminary operations the app is ready to use HomeKit!</p><p>Thanks for reading! I hope that this article has been useful for you. If you want to talk or have a coffee, contact or connect to me via LinkedIn: <a href="https://www.linkedin.com/in/francesco-merola-67654b245/"><em>Francesco.</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e335d2ac53b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>