<?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 Salah Nahed on Medium]]></title>
        <description><![CDATA[Stories by Salah Nahed on Medium]]></description>
        <link>https://medium.com/@salahamassi?source=rss-7b866121344a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*TljnX39arIsX-6eKFSdRAg.jpeg</url>
            <title>Stories by Salah Nahed on Medium</title>
            <link>https://medium.com/@salahamassi?source=rss-7b866121344a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 19:17:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@salahamassi/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[One Swift Protocol, Zero if-else: How WiNCH Reads Backend Permissions in iOS]]></title>
            <link>https://medium.com/@salahamassi/one-swift-protocol-zero-if-else-how-winch-reads-backend-permissions-in-ios-bfb419628b56?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb419628b56</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-apps]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Wed, 01 Jul 2026 21:00:11 GMT</pubDate>
            <atom:updated>2026-07-02T00:23:50.414Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QzjLyjr6p6lNyHRZ9aOetg.png" /></figure><p>Let me start with the ugly part, because that’s where every real story starts.</p><p>Before this system existed, permissions in WiNCH looked like this — everywhere:</p><pre>if user.permissions.contains(&quot;business.edit&quot;) {<br>    editButton.isHidden = false<br>} else {<br>    editButton.isHidden = true<br>}<br><br>if user.permissions.contains(&quot;business.update&quot;) {<br>    nameTextField.isUserInteractionEnabled = true<br>}<br><br>// ...and again, in the next view controller<br>// ...and again, in the cell<br>// ...and again, in the screen you forgot about<br></pre><p>The checks were not hard. That was never the problem. The problem was that they were <em>everywhere</em>. And “everywhere” has a cost you don’t feel on day one — you feel it three months later.</p><p>You can’t audit it. Nobody can look at one file and answer “what does this screen gate?” You can’t change it. The backend renames a permission key and now you’re grepping through forty view controllers. And it drifts. One screen hides the button, another disables it, a third forgets to check at all. Same permission, three different behaviors, zero consistency.</p><p>So we stopped writing permission <em>logic</em> and started writing permission <em>tags</em>.</p><h3>The one idea</h3><p>Here’s the whole trick, and everything else is just plumbing:</p><p><strong>A permission is not code. It’s metadata on a view.</strong></p><p>Instead of asking “should I show this button?” inside a view controller, the button itself carries the answer. You tag it once — &quot;edit&quot; — and the system figures out the rest. No if, no else, no view controller involved.</p><p>And because it’s metadata, we could set it in the one place iOS lets you attach metadata to a view without touching code: <strong>Interface Builder.</strong></p><h4>Where permissions come from</h4><p>Before the app side, the backend side. Nothing exotic here.</p><p>The user object comes down from the backend and carries a flat array of strings:</p><pre>{<br>  &quot;permissions&quot;: [<br>    &quot;business.edit&quot;,<br>    &quot;business.update&quot;,<br>    &quot;business.show&quot;,<br>    &quot;business.invoices.edit&quot;<br>  ]<br>}</pre><p>We cache that user once (at business/profile) and every view on every screen reads from that same cached array. One source of truth.</p><p>Notice the shape. Every key is namespaced with business., and the part after it is opaque — it can be a flat action like edit, or a resource-scoped key like invoices.edit. The app doesn&#39;t care. To the app it&#39;s just a string, and that&#39;s exactly why the system scales: it works the same whether you have five global flags or a hundred per-resource ones.</p><h3>The protocol</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j1Jcv8UGRyZlzyhicfGIlA.png" /></figure><p>Everything hangs off one small @MainActor protocol:</p><pre>@MainActor<br>public protocol HasPermission: AnyObject {<br>    var permission: String? { get set }<br>    func canView() -&gt; Bool<br>    func update(_ granted: Bool, updatePermision: Bool)<br>}</pre><p>Three things: the tag (permission), the question (canView()), and the reaction (update). Read it like a sentence — <em>this view has a permission, it can ask whether it&#39;s allowed, and it knows how to react.</em></p><p>The interesting part is canView() has a default implementation, so no conforming type has to write it:</p><pre>extension HasPermission {<br><br>    public var hasPermission: Bool {<br>        permission != nil<br>    }<br><br>    public func canView() -&gt; Bool {<br>        let appDataSource = WinchConfiguration.shared.appDataSource<br>        guard let user = appDataSource.getFromCache(path: &quot;business/profile&quot;, BusinessUser.self),<br>              let permission = permission else { return true }<br><br>        let userPermissions = user.permissions<br><br>        if permission.contains(&quot;|&quot;) {<br>            let permissions = permission<br>                .split(separator: &quot;|&quot;)<br>                .map { $0.trimmingCharacters(in: .whitespaces) }<br>            return permissions.contains { userPermissions.contains(&quot;business.\($0)&quot;) }<br>        } else {<br>            return userPermissions.contains(&quot;business.\(permission)&quot;)<br>        }<br>    }<br>}</pre><p>First, one name needs a quick word so it doesn’t read as magic: appDataSource is just WiNCH&#39;s cache. All the permission code ever asks of it is <em>read the object at a path</em> (getFromCache), <em>notify me when that path changes</em> (watch), and <em>stop</em> (unwatch) — it never knows or cares what storage sits behind that. Keep those three verbs in mind and every line below reads cleanly.</p><p>A few decisions live in this small block, and each one earned its place:</p><ul><li><strong>The </strong><strong>business. prefix is minted here, not stored.</strong> In Interface Builder you write the bare key &quot;edit&quot;. The business. gets glued on at check-time. So the tags stay short and readable, and if the namespace ever changes, it changes in one line.</li><li><strong>| gives you OR.</strong> Tag a view &quot;show|update&quot; and it&#39;s visible if the user has <em>either</em> one. We split on |, trim, and check if <em>any</em> match. Small feature, saves you from writing custom logic for &quot;this is visible to two roles.&quot;</li><li><strong>It fails open.</strong> No cached user, or no permission set → return true. This is a deliberate choice, and an honest one: I&#39;ll come back to it, because it&#39;s the part I&#39;d think hardest about before you copy this.</li></ul><h3>The real lesson: hide vs. disable</h3><p>This is the part I actually want you to take away, because it’s not a Swift trick — it’s a product decision that most permission systems get wrong.</p><p>Not being allowed to do something does not always mean you shouldn’t <em>see</em> it.</p><p>Sometimes “no permission” means <em>hide it</em> — you don’t get to know this button exists. But sometimes it means <em>show it, just locked</em> — you can see the field, you just can’t edit it. Preview mode. “You’re looking, not touching.”</p><p>Cramming both of those into isHidden is how you get a confusing app. So update handles the difference:</p><pre>public func update(_ granted: Bool, updatePermision: Bool) {<br>    if self is UITableViewCell {<br>        isUserInteractionEnabled = granted<br>        return<br>    }<br><br>    if let textField = self as? WinchTextFieldView {<br>        textField.justForPreview = !granted<br>        return<br>    }<br><br>    if let itemView = self as? WinchItemView, itemView.showSwitcher {<br>        itemView.switcher.isEnabled = granted<br>        return<br>    }<br><br>    if updatePermision {<br>        isUserInteractionEnabled = granted   // show it, lock it<br>    } else {<br>        isHidden = !granted                  // hide it entirely<br>    }<br>}</pre><p>Where does that updatePermision flag come from? It&#39;s decided the moment you set the tag — a single line in the property setter, updatePermision: permission?.contains(&quot;update&quot;). (We&#39;ll see the whole setter in a moment; for now the one line is the point.)</p><p>If the key contains &quot;update&quot;, we treat it as <em>disable</em>, not <em>hide</em>. Everything else defaults to hide. So a designer tags a text field &quot;update&quot; and it becomes read-only for users who can&#39;t edit — while a button tagged &quot;edit&quot; just vanishes for users who can&#39;t. Same system, two behaviors, decided by the tag, not by a view controller.</p><p>And notice the special cases at the top of update. A cell shouldn&#39;t disappear and leave a hole in your table — so we kill its interaction instead. A WinchTextFieldView has its own justForPreview state that&#39;s prettier than a hard disable. A WinchItemView with a switcher just disables the switch. The protocol gives every view a chance to react <em>in the way that makes sense for that view</em>, instead of forcing one behavior on all of them.</p><h3>The IBInspectable part (the fun one)</h3><p>Here’s what makes it disappear into the design process. That permission property is an @IBInspectable on a UIView extension:</p><pre>extension UIView: HasPermission {<br><br>    @IBInspectable<br>    public var permission: String? {<br>        get { objc_getAssociatedObject(self, &amp;AssociatedKeys.permission) as? String }<br>        set {<br>            objc_setAssociatedObject(self, &amp;AssociatedKeys.permission, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)<br>            update(canView(), updatePermision: permission?.contains(&quot;update&quot;) ?? false)<br>        }<br>    }<br>}</pre><p>Because it’s an extension on UIView, <strong>every view in the app gets a permission slot for free.</strong> Because it&#39;s @IBInspectable, that slot shows up as a text box in the Attributes Inspector in Interface Builder. And because stored properties aren&#39;t allowed in extensions, we back it with an associated object.</p><p>So the workflow becomes: open the storyboard, select a button, type edit in the Permission field. Done. The gate is now wired. No view controller learned a new line of code. The person wiring permissions doesn&#39;t even have to be the person who understands canView().</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZfjeKWQYTV-eHK1nhz0K8Q.png" /></figure><p>That’s the whole usage. Select the view, type branches.index, done.</p><p>The gate is now wired. No view controller learned a new line of code, and the person wiring permissions doesn&#39;t even have to be the person who understands canView() — they just need to know the key.</p><p>And notice that key: branches.index, not a bare edit. The string is opaque to the app, so it carries whatever structure your backend uses — a flat action like edit, or a resource-scoped key like branches.index (resource branches, action index).</p><p>At check time it becomes business.branches.index and gets matched against the user&#39;s permission list like any other.</p><p>Same machinery, whether you have five global flags or a hundred per-resource ones.</p><p>The moment you type that string, the setter fires update, which calls canView(), which reads the cached user — and the view configures itself before it&#39;s ever on screen.</p><p>We even extended it to NSLayoutConstraint, so a constraint can react to permissions too:</p><pre>extension NSLayoutConstraint: HasPermission {<br>    public func update(_ granted: Bool, updatePermision: Bool) {<br>        constant = granted ? .zero : -200<br>    }<br>}</pre><p>I’ll be honest with you: that -200 is a hack. It collapses the constrained space when the permission is denied, so you don&#39;t leave an empty gap in the layout where the hidden view used to be. It works, it shipped, and I still wince at the magic number. If I were doing it again I&#39;d make that value configurable instead of hard-coding it.</p><p>Real production code has these. Pretending it doesn&#39;t is how you write tutorials nobody trusts.</p><h3>But permissions change while you’re looking at them</h3><p>Everything so far happens at <em>load time</em>. You set the tag, the setter fires update, the view configures itself before it hits the screen. Good — but not enough.</p><p>Permissions aren’t frozen. A manager grants you edit rights. You switch business accounts. The profile refreshes in the background. When that happens, the user object in our cache changes — and every screen already visible is now showing <em>stale</em> permissions. The button that should have appeared is still hidden. The field that should have unlocked is still read-only.</p><p>So the base view controller watches the cache and re-applies permissions to the whole screen when the user changes. This lives in NibViewController, which every screen in WiNCH inherits from:</p><pre>open override func viewWillAppear(_ animated: Bool) {<br>    super.viewWillAppear(animated)<br>    observeUserCacheChange()<br>}<br><br>open override func viewWillDisappear(_ animated: Bool) {<br>    super.viewWillDisappear(animated)<br>    WinchConfiguration.shared.appDataSource.unwatch(object: self)<br>}<br><br>private func observeUserCacheChange() {<br>    let appDataSource = WinchConfiguration.shared.appDataSource<br>    appDataSource.watch(path: &quot;business/profile&quot;, object: self) { [weak self] _ in<br>        guard let self = self else { return }<br>        self.updatePermissionViews(in: view)<br>    }<br>}</pre><p>We watch the same cache key the permissions read from — business/profile — the single source of truth again. The moment it changes, we don&#39;t reload the screen, rebuild the view controller, or pop anything. We just re-ask every tagged view the same question it answered at load time:</p><pre>private func updatePermissionViews(in rootView: UIView) {<br>    for subview in rootView.subviews {<br>        let permissionView = subview as HasPermission<br>        if let permission = permissionView.permission {<br>            permissionView.update(permissionView.canView(),<br>                                  updatePermision: permission.contains(&quot;update&quot;))<br>        }<br><br>        for constraint in subview.constraints {<br>            let permissionConstraint = constraint as HasPermission<br>            if permissionConstraint.permission != nil {<br>                permissionConstraint.update(permissionConstraint.canView(),<br>                                            updatePermision: false)<br>            }<br>        }<br><br>        updatePermissionViews(in: subview)   // recurse<br>    }<br>}</pre><p>This walks the entire view tree, depth first. Every UIView conforms to HasPermission — that&#39;s why the cast is as, not as?, it never fails — but only the views actually carrying a tag react. Same for constraints. One pass, and the whole screen snaps to the new permission state. Buttons appear, fields unlock, layout collapses — live, with the user watching, no navigation required.</p><p>That’s the piece that turns this from a set-once gate into something reactive. The tag says <em>what</em> to check; the setter checks it at load; and this watch re-checks it whenever the answer might have changed. Three moments, one question.</p><p>(One honest edge: the walk starts at view.subviews, so a permission tag on the root view itself — or a constraint owned by it — wouldn&#39;t be picked up by the refresh. In practice nobody tags the root view, but it&#39;s the kind of gap worth knowing is there.)</p><h4>The one thing to think hard about: it fails open</h4><pre>guard let user = ... , let permission = permission else { return true }</pre><p>No user in cache → allowed. This is fine for WiNCH’s model, where a view with no permission tag is genuinely public, and where the cached user is reliably there by the time these views render. But “fail open” is a security posture, and you should choose it on purpose, not inherit it by accident. If you adapt this, ask yourself: in <em>your</em> app, is the safer default to show or to hide when you’re unsure? For a lot of apps the answer flips to return false. Know which one you&#39;re picking.</p><h3>What if WiNCH ran with SwiftUI? Could we use the same approach?</h3><p><strong>Short answer: no to the mechanism, yes to the idea.</strong></p><p>The mechanism dies in SwiftUI. This whole system is built on UIKit bones — @IBInspectable (there&#39;s no Interface Builder), associated objects on UIView (SwiftUI views are value-type structs, not reference-type classes), and mutating isHidden / isUserInteractionEnabled on a live view instance. None of that exists in SwiftUI.</p><p>But the <em>philosophy</em> — a permission is a declarative tag on a view, not if-else in your logic — fits SwiftUI even better than UIKit. You&#39;d just express it as a ViewModifier instead of an inspectable property:</p><pre>struct PermissionModifier: ViewModifier {<br>    let permission: String<br><br>    func body(content: Content) -&gt; some View {<br>        if canView(permission) {<br>            content<br>        } else if permission.contains(&quot;update&quot;) {<br>            content.disabled(true)   // show, locked<br>        }                            // else: renders nothing → hidden<br>    }<br>}<br><br>extension View {<br>    func permission(_ key: String) -&gt; some View {<br>        modifier(PermissionModifier(permission: key))<br>    }<br>}</pre><pre>EditButton()<br>    .permission(&quot;edit&quot;)<br><br>NameField()<br>    .permission(&quot;update&quot;)   // visible but disabled without rights</pre><p>Same three ideas survive the port intact: the tag, the check, the hide-vs-disable split. What changes is only <em>how</em> you attach the tag — an inspector text box becomes a modifier. That’s the real signal that this was a good design in the first place: the core idea outlives the framework it was born in.</p><h3>Conclusion</h3><p>We didn’t make permission checks smarter. We made them <em>disappear</em> — out of view controllers and into the views themselves, where they read as data instead of logic. One protocol, a default canView(), and an update that respects the difference between &quot;you can&#39;t see this&quot; and &quot;you can&#39;t touch this.&quot;</p><p>The if-else didn&#39;t get cleaner. It got deleted.</p><h3>About me</h3><p>I’m Salah — a Senior Mobile Engineer with 7+ years across iOS (Swift, UIKit, SwiftUI) and Flutter. I care about the unglamorous parts: the patterns that keep production code from rotting, and the abstractions that <em>delete</em> code instead of piling more on. WiNCH’s permission system is one of those, and I write about the rest as I ship them.</p><p>I build in the open too — <a href="https://medium.com/LINK"><strong>AppRouter-UIKit</strong></a> and <a href="https://medium.com/LINK"><strong>Flutter Bond</strong></a> — and share smaller Swift and Flutter patterns across my channels.</p><p><strong>I’m currently open to new opportunities</strong> — senior mobile roles, remote or relocation. If your team builds things properly and sweats the details, I’d love to talk.</p><ul><li>Website — <a href="http://salahnahed.dev/">salahnahed.dev</a></li><li>LinkedIn —<a href="https://www.linkedin.com/in/salah-nahed-a73250135/"> /in/salah_nahed</a></li><li>GitHub — <a href="https://github.com/salahamassi">/salahamassi</a></li><li>Instagram /<a href="https://www.instagram.com/salahamassi">salahamassi</a></li></ul><p><em>If this saved you an afternoon of </em><em>if-else archaeology, a follow means a lot — more production patterns are on the way.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb419628b56" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Protocol Magic II: Designing a Reusable Location Tracking System]]></title>
            <link>https://medium.com/@salahamassi/swift-protocol-magic-ii-designing-a-reusable-location-tracking-system-9ae7296dd16b?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ae7296dd16b</guid>
            <category><![CDATA[protocol-oriented]]></category>
            <category><![CDATA[ios-apps]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Fri, 15 May 2026 00:26:00 GMT</pubDate>
            <atom:updated>2026-05-15T00:26:00.639Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2tRZQUWVuehzDP2G6T7fhw.png" /></figure><p><em>How to stop rewriting </em><em>CLLocationManager boilerplate in every screen — and design something your future self will actually thank you for.</em></p><p>If you’ve shipped more than a couple of iOS apps, you’ve written this code. Probably more than once. Maybe more than ten times.</p><pre>locationManager.delegate = self<br>locationManager.requestWhenInUseAuthorization()<br>// ...somewhere else...<br>func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>    // do the thing<br>}</pre><p>And every time, you end up with the same scattered mess: a CLLocationManager instance hanging off a view controller, delegate methods sprinkled in between unrelated UI code, an if ladder for authorization status, and some half-built UI for telling the user <em>&quot;hey, you actually need to enable location for this to work.&quot;</em></p><p>It works. But it doesn’t <em>scale</em> across an app. The second screen that needs location duplicates 80% of the first one. The third screen tweaks just enough to make extraction painful. By the fifth screen, you’re copy-pasting and praying.</p><p>I hit this exact wall on <strong>WinchCore</strong>, the shared layer behind a production app I’m building. So I sat down and asked the question I should have asked years ago:</p><blockquote><em>What if a view controller could become “location-aware” just by conforming to a protocol — and the framework handled the rest?</em></blockquote><p>This article walks through the design I landed on. It’s four small files, but they compose into something I keep reaching for in screen after screen. Let’s get into it.</p><h3>The wishlist</h3><p>Before any code, here’s what I wanted out of this:</p><ol><li><strong>Any view controller</strong> should be able to opt into location tracking by conforming to a protocol — no inheritance, no base class.</li><li><strong>Authorization handling</strong> (the denied/restricted screen, the “please enable location” UI) should be centralized, not re-implemented per screen.</li><li><strong>The restriction UI should be configurable</strong> — different screens want different titles, subtitles, and behaviors. Some screens <em>must</em> have location (a map). Others can tolerate the user dismissing the prompt (a profile screen showing nearby suggestions).</li><li><strong>Testable.</strong> The whole point of touching this code was to make it possible to swap CLLocationManager for a fake in tests.</li><li><strong>No surprises.</strong> When the screen appears, location updates start. When the user denies permission, the right UI shows up. That’s it.</li></ol><p>Four protocols. One concrete class. Let’s walk through them in the order they make sense to read.</p><h3>Piece 1: LocationManager — the abstraction</h3><pre>public protocol LocationManager: CLLocationManagerDelegate {<br>    func startTrackingLocation()<br>    func startUpdatingLocation()<br>    var currentLocation: CLLocation? { get }<br>}</pre><p>That’s it. The whole protocol.</p><p>The trick here is that it inherits from CLLocationManagerDelegate. That way any concrete implementation already has the delegate surface it needs, and from the call site you never have to think about CLLocationManager directly. You think about &quot;tracking&quot; and &quot;updating&quot; — verbs that match what your screen actually wants to do.</p><p>startTrackingLocation() is the &quot;I just appeared, start the whole flow&quot; entry point — authorization, delegate setup, all of it.</p><p>startUpdatingLocation() is the &quot;I already have permission, just give me a fresh fix&quot; version — useful when the user taps a refresh button, for example.</p><p>currentLocation is a snapshot accessor for the cases where you just want the last known coordinate without subscribing to anything.</p><p>This is the seam where testing gets easy. In a unit test, you don’t construct a CLLocationManager. You construct a mock that conforms to LocationManager, return whatever location you want, and assert on what the screen does with it. No simulator GPS, no Info.plist dance, no flakiness.</p><h3>Piece 2: TrackableLocationViewController — making any VC location-aware</h3><pre>public protocol TrackableLocationViewController: UIViewController {<br>    func handleLocationUpdate(lat: Double, lng: Double) async<br>    var locationManager: LocationManager { get }<br>}</pre><p>This is the protocol your view controller conforms to. It says two things:</p><ul><li>“I own a LocationManager.&quot;</li><li>“When a location update arrives, here’s what I want to do with it.”</li></ul><p>The fact that handleLocationUpdate is async is intentional.</p><p>Most of the time, when a location comes in, you&#39;re not just updating a label — you&#39;re firing off a network call to fetch nearby data, hitting a geocoder, or syncing with a backend.</p><p>Making the contract async from the start means the manager can await the screen&#39;s work without us bolting on Combine pipelines or completion handler hell later.</p><p>And here’s where protocol extensions earn their keep:</p><pre>public extension TrackableLocationViewController {<br>    func startTrackingLocation() {<br>        locationManager.startTrackingLocation()<br>    }<br><br>    func startUpdatingLocation() {<br>        locationManager.startUpdatingLocation()<br>    }<br><br>    var currentLocation: CLLocation? {<br>        locationManager.currentLocation<br>    }<br>}</pre><p>Free methods. The view controller didn’t write any of this — it just gets it by conforming. Now any conforming screen can call self.startTrackingLocation() in viewDidLoad() and the system takes over.</p><p>The usage looks like this:</p><pre>class MapViewController: NibViewController, TrackableLocationViewController {<br><br>    private lazy var appLocationManager: AppLocationManager = {<br>        AppLocationManager(locationManager: CLLocationManager(), viewController: self)<br>    }()<br><br>    var locationManager: LocationManager { appLocationManager }<br><br>    func handleLocationUpdate(lat: Double, lng: Double) async {<br>        mapView.setCenter(CLLocationCoordinate2D(latitude: lat, longitude: lng), animated: true)<br>        await fetchNearbyPlaces(lat: lat, lng: lng)<br>    }<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        startTrackingLocation()<br>    }<br>}</pre><p>Three lines of contract. The rest is your screen’s actual job.</p><h3>Piece 3: LocationRestrictionConfigurable — the &quot;you blocked us, now what?&quot; protocol</h3><p>This is the piece I’m most proud of, because it’s the one that usually gets hacked together five different ways across an app.</p><p>When the user denies location, you need to show <em>something</em>. A screen, an alert, a banner — whatever your designer decided. And that something is almost never identical across screens. The map screen probably wants a full-screen blocker that says <em>“Enable location to see places near you.”</em> The profile screen might want a softer, dismissible message. Different titles, different subtitles, different blocking behavior.</p><p>So instead of hardcoding any of that into the location manager, I made it configurable through another protocol:</p><pre>public protocol LocationRestrictionConfigurable: TrackableLocationViewController {<br>    var titleText: String? { get }<br>    var subtitle: String? { get }<br>    var shouldBlock: Bool { get }<br>}</pre><p>Three properties. Each screen decides what it wants. And — critically — the protocol extends TrackableLocationViewController, so anywhere we need both behaviors we can compose them with the &amp; operator and Swift&#39;s type system enforces it.</p><p>But here’s the part I love: default values via protocol extension.</p><pre>public extension LocationRestrictionConfigurable {<br>    var titleText: String? { nil }<br>    var subtitle: String? { nil }<br>    var shouldBlock: Bool { false }<br>}</pre><p>If a screen doesn’t care, it conforms and ignores. If a screen <em>does</em> care, it overrides just the properties it needs. No required boilerplate. No // TODO: configure this landmines.</p><p>The shouldBlock flag is the small detail that captures a real product question: <em>can the user leave this screen without enabling location?</em> For a map showing nearby drivers, the answer is no — the screen would be useless. For a search screen with optional location filtering, the answer is yes. The flag pushes that decision back where it belongs: with the screen itself, not with some central authorization handler making assumptions.</p><h3>Piece 4: AppLocationManager — the concrete glue</h3><p>This is where it all comes together. The full file is on the longer side, so let’s read it in chunks.</p><h3>The init</h3><pre>@MainActor<br>public class AppLocationManager: NSObject, LocationManager {<br><br>    private let locationManager: CLLocationManager<br>    private let viewController: TrackableLocationViewController &amp; LocationRestrictionConfigurable<br><br>    public init(locationManager: CLLocationManager,<br>                viewController: TrackableLocationViewController &amp; LocationRestrictionConfigurable) {<br>        self.locationManager = locationManager<br>        self.viewController = viewController<br>    }<br>}</pre><p>Two things to notice.</p><p>First, <strong>@MainActor</strong>. Location callbacks touch the UI — they trigger navigation, update maps, etc. By marking the whole class @MainActor, every callback is guaranteed to run on the main thread.</p><p>You don’t need to wrap every callback in DispatchQueue.main.async just to be safe.</p><p>Second, the <strong>composed type</strong> in the initializer:</p><pre>viewController: TrackableLocationViewController &amp; LocationRestrictionConfigurable</pre><p>This is the Swift type system doing real work for us. You literally cannot construct an AppLocationManager with a view controller that hasn&#39;t said &quot;yes, I will track location&quot; <em>and</em> &quot;yes, I will configure my restriction UI.&quot; If you try, the compiler stops you. Bug prevented before it exists.</p><h3>The deliberate delay</h3><pre>public func startTrackingLocation() {<br>    print(&quot;startTrackingLocation called from \(type(of: viewController))&quot;)<br>    DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [weak self] in<br>        guard let self = self else { return }<br>        self.locationManager.delegate = self<br>        let status = self.locationManager.authorizationStatus<br>        self.handleLocationAuthorization(status: status)<br>    }<br>}</pre><p>That one-second delay isn’t laziness — it’s intentional. When a screen appears, you usually want the skeleton/loading state to render <em>first</em>, then the permission prompt or the restriction UI to come up. If the system permission alert fires the instant viewDidLoad runs, you get a jarring experience: blank screen → modal alert → screen finally renders. Adding a small delay lets the UI breathe.</p><p>This is the kind of decision you don’t see in tutorials, but you absolutely feel in production.</p><h3>The authorization switch — and the nested router fallback</h3><pre>private func handleLocationAuthorization(status: CLAuthorizationStatus) {<br>    switch status {<br>    case .notDetermined:<br>        locationManager.requestWhenInUseAuthorization()<br>    case .restricted, .denied:<br>        if let router = viewController.nestedRouter {<br>            router.navigate(to: .locationRestricted(<br>                nested: true,<br>                title: viewController.titleText,<br>                subtitle: viewController.subtitle,<br>                shouldBlock: viewController.shouldBlock<br>            ))<br>        } else {<br>            viewController.router?.navigate(to: .locationRestricted(<br>                nested: false,<br>                title: viewController.titleText,<br>                subtitle: viewController.subtitle,<br>                shouldBlock: viewController.shouldBlock<br>            ))<br>        }<br>    case .authorizedAlways, .authorizedWhenInUse:<br>        locationManager.startUpdatingLocation()<br>    @unknown default:<br>        fatalError(&quot;Unknown authorization status.&quot;)<br>    }<br>}</pre><p>The notDetermined and authorized cases are mechanical. The interesting case is .restricted, .denied.</p><p>When location is denied, the manager asks the view controller: <em>do you have a nested router?</em> If you’re a child controller inside a tab bar or a container view controller, you probably want the restriction screen to present <em>inside</em> your container, not over the entire app. The nestedRouter is the seam for that. If there&#39;s no nested router, we fall back to the screen&#39;s main router and present it normally.</p><p>This is a small thing, but it’s the kind of detail that turns a “decent abstraction” into “an abstraction I actually want to use in every screen.” Real apps have nested navigation. The framework should know that.</p><h3>The delegate methods</h3><pre>extension AppLocationManager {<br>    public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {<br>        guard let location = locations.last else { return }<br>        if location.coordinate.latitude == 0 || location.coordinate.longitude == 0 { return }<br><br>        Task {<br>            await viewController.handleLocationUpdate(lat: location.coordinate.latitude,<br>                                                      lng: location.coordinate.longitude)<br>        }<br>        manager.stopUpdatingLocation()<br>    }<br><br>    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {<br>        handleLocationAuthorization(status: status)<br>    }<br><br>    public func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {<br>        print(&quot;AppLocationManager locationManager error: \(error)&quot;)<br>    }<br>}</pre><h3>Three things to point out:</h3><ol><li><strong>The (0, 0) guard.</strong> On rare occasions, CLLocationManager will hand you a coordinate of (0, 0) — which is technically a real place in the Atlantic Ocean off the coast of Africa, but practically always means the GPS hasn&#39;t acquired a real fix yet. Filtering those out is a small piece of defensive code that saves you from rendering a map of the open sea.</li><li><strong>Task { await ... } bridges the worlds.</strong> The delegate callback is synchronous, but handleLocationUpdate is async. Wrapping it in a Task lets the screen&#39;s async work run without blocking the delegate.</li><li><strong>stopUpdatingLocation() after the first fix.</strong> This particular flow is one-shot — we want a single accurate location, not a continuous stream. If you needed continuous tracking (turn-by-turn navigation, fitness tracking), you&#39;d skip this line. But for &quot;where is the user <em>right now</em> so I can fetch nearby data,&quot; one fix is usually enough, and it&#39;s much better for battery.</li></ol><h3>Why this design pays off</h3><p>Let me zoom out, because the pieces individually are small, but the system they form is the point.</p><p><strong>Adding location tracking to a new screen takes about five lines.</strong> Conform to the two protocols, provide a LocationManager, implement handleLocationUpdate, call startTrackingLocation() in viewDidLoad. Done. Every other concern — authorization, restriction UI, blocking behavior, threading — is handled.</p><p><strong>Testing is trivial.</strong> Mock LocationManager, feed it whatever location you want, assert on what handleLocationUpdate does. No real GPS, no real CLLocationManager, no flakiness.</p><p><strong>Customization is opt-in.</strong> Want a different restriction title for this screen? Override titleText. Want this screen to block until location is enabled? Set shouldBlock to true. Don&#39;t care? Conform and move on with your day.</p><p><strong>The compiler enforces the contract.</strong> You can’t construct an AppLocationManager with a view controller that&#39;s missing either protocol. The bug where someone forgets to handle restriction UI literally cannot exist.</p><p><strong>The main thread is guaranteed.</strong> @MainActor removes a whole category of &quot;why is my UI updating weirdly&quot; bugs that come from delegate callbacks not being on the main thread.</p><h3>What I’d add next</h3><p>Honest reflection — this design isn’t done. Things I’d evolve in a future version:</p><ul><li><strong>Continuous tracking mode.</strong> Right now it’s one-shot. A TrackingMode enum (oneShot, continuous, significantChanges) would make it more flexible.</li><li><strong>Last-known-location caching.</strong> For screens that just want a rough location to fetch initial data, returning the last cached fix immediately would feel snappier.</li><li><strong>Background location</strong> — a whole separate beast that deserves its own protocol layer.</li><li><strong>Replace </strong><strong>print with a proper logger</strong> — the current print statements were debugging aids that lingered. A real app should route these through os.Logger or whatever your logging story is.</li></ul><p>But none of these change the core shape. They extend it.</p><h3>Takeaways</h3><p>If you take one thing from this, let it be this: <strong>the magic isn’t the code, it’s the seams.</strong></p><p>The seams are where you draw the lines between what a view controller knows and what the framework handles. Protocols are the tool for drawing those lines cleanly. Default implementations are how you keep them ergonomic. Composed types (A &amp; B) are how you let the compiler enforce them.</p><p>When you find yourself copy-pasting the same setup code into yet another view controller, that’s the signal. There’s a protocol hiding in there. Pull it out, give it defaults, compose it with what’s already there.</p><p>That’s all “Protocol Magic” really is — recognizing those moments and acting on them.</p><p>If you found this useful, the <a href="https://github.com/salahamassi/AppRouter-UIKit">AppRouter-UIKit</a> library I open-sourced uses similar patterns for navigation.</p><p>And if you missed part one — &quot;<a href="https://medium.com/@salahamassi/swift-protocol-magic-building-a-beautiful-reusable-option-selection-system-bcb76adead7c">Swift Protocol Magic: Building a Beautiful Reusable Option Selection System</a>&quot; — it covers the same approach applied to bottom sheets and option pickers.</p><p>👋 <strong>A quick note:</strong> I’m currently open to new opportunities. After 7+ years building iOS apps (and Flutter more recently), I’m looking to join an amazing team — ideally an international, on-site role — where I can keep building things like this. If your team is hiring, or you just want to talk iOS architecture, please reach out on any channel below.</p><p>📩 <a href="https://www.linkedin.com/in/salah-amassi-a73250135/"><strong>Connect with me on LinkedIn</strong></a> Follow my tech journey</p><p>🐙 GitHub: <a href="https://github.com/salahamassi"><strong>salahamassi</strong></a></p><p>📸 Instagram: <a href="https://instagram.com/salahamassi"><strong>@salahamassi</strong></a></p><p>Let’s build something elegant together. ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ae7296dd16b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Design-Driven Firebase in Flutter: Building Custom In-App Messaging with SwiftUI & Compose]]></title>
            <link>https://medium.com/@salahamassi/design-driven-firebase-in-flutter-building-custom-in-app-messaging-with-swiftui-compose-ff2b7875d8a7?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2b7875d8a7</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[jetpack-compose]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Thu, 10 Apr 2025 23:29:38 GMT</pubDate>
            <atom:updated>2025-04-12T13:52:32.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e7ZIh59rCE6S02cjIVIP7Q.png" /></figure><h3>Introduction</h3><p>In-app messaging plays a critical role in how users interact with modern apps — from promoting offers to driving engagement and retention. While Firebase In-App Messaging (FIAM) provides a quick and powerful way to deliver contextual messages to users, its default layouts can feel limiting when your brand demands a refined, custom look and feel.</p><p>This article walks you through our journey of building a fully customized FIAM experience for both iOS and Android using <strong>SwiftUI</strong> and <strong>Jetpack Compose</strong> — the modern declarative UI frameworks of their respective platforms. More than just a UI overhaul, this work was about enabling <strong>design-driven communication</strong>, deeply integrated with analytics, user behavior, and growth strategy.</p><p>Coming from a background where I often had to stretch limited tools to achieve polished results, I’ve learned to appreciate the subtle elegance of design and the value of seamless integration. This wasn’t just an engineering challenge — it was a creative one. And honestly, I loved every bit of it.</p><p>You’ll discover why we chose not to reinvent the wheel with a custom messaging service, what we would have missed by bypassing Firebase, and how we overcame the surprising limitations (and lack of documentation) in Firebase’s SDK. From crafting a polished UI to handling deep links seamlessly, this story is a blend of product empathy, platform mastery, and personal grit.</p><p>If you’re working on a Flutter app or a hybrid mobile solution, and want the best of both Firebase’s backend and full visual control, you’re in the right place.</p><h3>📚 Table of Contents</h3><ol><li><a href="#8bfd">Why We Needed This Customization</a></li><li><a href="#8bfd">Why We Didn’t Build Our Own Messaging System</a></li><li><a href="#0349">What About Flutter?</a></li><li><a href="#44ce">Our Implementation Plan</a></li><li><a href="#219d">iOS: SwiftUI</a></li><li><a href="#ce0e">Android: Jetpack Compose</a></li><li><a href="#f64d">Deep Link &amp; Platform Differences</a></li><li><a href="#2bf8">How to Test In-App Messages</a></li><li><a href="#8e09">About Deep Links</a></li><li><a href="#3232">Final Thoughts + Who Am I</a></li></ol><h3><strong>Why We Needed This Customization</strong></h3><p>Firebase In-App Messaging (FIAM) offers a solid out-of-the-box solution with predefined layouts like modals and banners, but when we actually tried using them, it became clear they weren’t enough.</p><p>We needed to:</p><ul><li>Match our <strong>brand style</strong> and UI system — rounded corners, layout spacing, colors, fonts.</li><li>Add support for <strong>secondary actions</strong> and dynamic content not supported in default FIAM templates.</li></ul><p>The default templates were too limited, and we wanted a design that feels like a real part of the app — not a generic pop-up.</p><h3><strong>Why We Didn’t Build Our Own Messaging System</strong></h3><p>It might be tempting to create a completely custom in-app messaging feature using our own backend or CMS — but we would’ve lost far more than we’d gain.</p><p>Firebase offers:</p><ul><li><strong>Event-based targeting</strong>, allowing messages to appear based on user actions.</li><li>Seamless <strong>integration with Firebase Analytics</strong>, giving insights into message performance.</li><li><strong>A/B testing and personalization</strong>, without building an internal toolset.</li><li><strong>Rich scheduling and targeting rules</strong>, all manageable from the Firebase Console.</li></ul><p>In other words, FIAM already provides the hard stuff — <em>when</em> and <em>why</em> to show the message. All we needed was control over the <em>how</em>.</p><h3><strong>What About Flutter?</strong></h3><p>You might be wondering:</p><blockquote><em>“If we’re building a Flutter app, why are we dealing with all this native code?”</em></blockquote><p>Great question.</p><p>Although your app is Flutter, Firebase In-App Messaging (FIAM) is <strong>a native SDK</strong> — and it <strong>renders messages outside of your Flutter widget tree</strong>.</p><p>So if you want full control over how messages appear, behave, and connect back into your Flutter experience…</p><p>You <strong>must</strong> customize it on the <strong>native layer</strong>.</p><h4><strong>🎯 Why All This Native Work?</strong></h4><p>Even in a fully Flutter app, we still needed to:</p><p>• Customize message layout with <strong>SwiftUI</strong> on iOS and <strong>Jetpack Compose</strong> on Android.</p><p>• Handle deep links, apply themes, and dismiss messages gracefully.</p><p>• Call messageClicked() and messageDismissed() to <strong>report user interaction</strong> back to Firebase.</p><p>• Let Firebase still track analytics, impressions, and conversion events.</p><p>All this is invisible to Flutter — but critical to delivering the right message at the right time, with the right UX.</p><h4><strong>⚠️ Limited to Modal Messages</strong></h4><p>Our custom layout <strong>only supports modal messages</strong>.</p><p>If you choose a <strong>banner</strong>, <strong>image-only</strong>, or <strong>card-style</strong> message from the Firebase dashboard, it won’t appear with our custom UI. Instead, Firebase will fall back to its default look — and it might look out of place inside your Flutter app.</p><p>So:</p><blockquote><em>🛑 Be sure to select </em><strong><em>Modal</em></strong><em> as your layout in Firebase if you want the custom experience.</em></blockquote><h3><strong>Our Plan (and the Docs That Barely Helped)</strong></h3><p>Firebase officially supports custom in-app message layouts… kind of.</p><h4><strong>📱 On iOS:</strong></h4><p>The docs mention you can conform to the InAppMessagingDisplay protocol and assign your custom implementation using:</p><pre>InAppMessaging.inAppMessaging().messageDisplayComponent = yourInstance</pre><p>But there’s no real example. Just a reference to a header file and a vague tip to “look at the default SDK code.” Helpful? Not really.</p><h4><strong>🤖 On Android:</strong></h4><p>Slightly better — you’re told to implement the FirebaseInAppMessagingDisplay interface and register it using:</p><pre>FirebaseInAppMessaging.getInstance().setMessageDisplayComponent(yourInstance)</pre><p>But again, no Compose or Jetpack-style example. Just a reference to a legacy FirebaseInAppMessagingDisplayImpl.java.</p><h4><strong>🐦 On Flutter:</strong></h4><p>There is <strong>zero</strong> documentation.</p><p>Firebase’s Flutter SDK does not expose setMessageDisplayComponent, nor does it mention that you can override rendering — but since the native SDKs support it, we took the long route: inject a native custom display component from Kotlin and Swift that does the job behind the scenes.</p><h4><strong>Our Implementation Plan</strong></h4><p>Since Firebase gives us the data but not the design, we decided to:</p><ul><li><strong>Use the native SDKs</strong> for their logic and event triggers.</li><li><strong>Replace the UI layer</strong> with custom layouts using <strong>SwiftUI</strong> on iOS and <strong>Jetpack Compose</strong> on Android.</li><li><strong>Trigger navigation</strong> via deep links back into Flutter, bridging the two worlds.</li><li>Support additional customization like dynamic text, styling, secondary actions, and even design tokens via Firebase’s appData.</li></ul><p>The result? A deeply integrated, native-feeling experience powered by Firebase’s brains and our app’s personality.</p><p>Final result will be something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*agnefKKSVb-e9suOhuEn-A.png" /></figure><h3><strong>Starting with iOS: SwiftUI Makes It a Breeze</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-Xp_S9vanJjqAqiaXDH6A.png" /></figure><p>We began our custom layout journey on iOS, and thankfully, SwiftUI made the process <em>way</em> smoother than expected. No need for hacky integrations or major SDK rewrites — just make sure your <strong>deployment target is iOS 13+</strong>, and you’re ready to roll.</p><p>Firebase gives you everything you need to start displaying custom in-app messages — as long as you know <strong>where to plug in</strong>. Here’s what we did:</p><h4><strong>🧱 Files we created:</strong></h4><p>• <strong>NologyInAppMessageRenderer.swift</strong>: Our custom renderer that conforms to InAppMessagingDisplay.</p><p>• <strong>FullScreenInAppMessageView.swift</strong>: A simple SwiftUI view that handles layout, image rendering, and buttons.</p><p>• <strong>InAppButtonStyle.swift</strong>: A struct to hold button styles and colors.</p><p>• <strong>Extensions+Color.swift</strong>: Just a few helpers to convert hex strings to SwiftUI colors.</p><h4>Step 1: Define a Reusable Button Style</h4><pre>import SwiftUI<br><br>struct InAppButtonStyle {<br>    let title: String<br>    let textColor: Color<br>    let backgroundColor: Color<br>}</pre><p>This struct simply holds the text and color information for a button, allowing us to easily pass around consistent button data when rendering the view.</p><h4>Step 2: Create the Full-Screen In-App Message View</h4><p>Next, we define the layout of the message using SwiftUI. We want a background image with optional primary and secondary buttons stacked at the bottom.</p><pre>import SwiftUI<br><br>struct FullScreenInAppMessageView: View {<br>    let image: UIImage<br>    let primaryButton: InAppButtonStyle<br>    let secondaryButton: InAppButtonStyle?<br>    let onPrimary: () -&gt; Void<br>    let onSecondary: () -&gt; Void<br><br>    var body: some View {<br>        let screen = UIScreen.main.bounds<br>        let width = screen.width - 48<br>        let height = screen.height * 0.75<br><br>        return ZStack {<br>            Color.black.opacity(0.5).edgesIgnoringSafeArea(.all)<br><br>            Image(uiImage: image)<br>                .resizable()<br>                .aspectRatio(contentMode: .fill)<br>                .frame(width: width, height: height)<br>                .clipped()<br>                .cornerRadius(24)<br>                .overlay(buttonOverlay, alignment: .bottom)<br>        }<br>    }<br><br>    private var buttonOverlay: some View {<br>        VStack {<br>            Spacer()<br><br>            HStack(spacing: 16) {<br>                if let secondary = secondaryButton {<br>                    Button(action: onSecondary) {<br>                        Text(secondary.title)<br>                            .foregroundColor(secondary.textColor)<br>                            .padding(.vertical, 10)<br>                            .frame(maxWidth: .infinity)<br>                            .background(secondary.backgroundColor)<br>                            .cornerRadius(12)<br>                    }<br>                }<br><br>                Button(action: onPrimary) {<br>                    Text(primaryButton.title)<br>                        .foregroundColor(primaryButton.textColor)<br>                        .padding(.vertical, 10)<br>                        .frame(maxWidth: .infinity)<br>                        .background(primaryButton.backgroundColor)<br>                        .cornerRadius(12)<br>                }<br>            }<br>            .padding(.horizontal, 20)<br>            .padding(.bottom, 24)<br>        }<br>    }<br>}</pre><p>This view shows the image and stacks buttons over it. Now that the UI is ready, the next step is integrating it into the Firebase system. Let’s look at the custom renderer next.</p><h4><strong>Step 3: Creating a Custom In-App Message Renderer</strong></h4><pre>import FirebaseInAppMessaging<br>import SwiftUI<br>import UIKit<br><br>class NologyInAppMessageRenderer: NSObject, InAppMessagingDisplay {<br>    func displayMessage(_ message: InAppMessagingDisplayMessage,<br>                        displayDelegate: InAppMessagingDisplayDelegate) {<br>        DispatchQueue.main.async {<br>            // Get the app&#39;s main window<br>            guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,<br>                  let window = windowScene.windows.first(where: { $0.isKeyWindow }) else { return }<br><br>            // Only support modal messages for now<br>            guard let modal = message as? InAppMessagingModalDisplay else {<br>                print(&quot;Message is not a modal type.&quot;)<br>                return<br>            }<br><br>            // Decode image data<br>            guard let imageData = modal.imageData,<br>                  let rawData = imageData.imageRawData,<br>                  let image = UIImage(data: rawData) else {<br>                print(&quot;No image found.&quot;)<br>                return<br>            }<br><br>            // Prepare the primary button style<br>            guard let actionButton = modal.actionButton,<br>                  let actionURL = modal.actionURL else {<br>                print(&quot;Missing action button or URL.&quot;)<br>                return<br>            }<br><br>            let primaryStyle = InAppButtonStyle(<br>                title: actionButton.buttonText,<br>                textColor: Color(cgColor: actionButton.buttonTextColor.cgColor),<br>                backgroundColor: Color(cgColor: actionButton.buttonBackgroundColor.cgColor)<br>            )<br><br>            // Optional secondary button from custom appData<br>            var secondaryStyle: InAppButtonStyle? = nil<br>            if let appData = message.appData,<br>               let title = appData[&quot;secondaryTitle&quot;] as? String,<br>               let textColorHex = appData[&quot;secondaryTextColor&quot;] as? String,<br>               let backgroundHex = appData[&quot;secondaryBackgroundColor&quot;] as? String,<br>               let textColor = Color(hex: textColorHex),<br>               let backgroundColor = Color(hex: backgroundHex) {<br>                <br>                secondaryStyle = InAppButtonStyle(<br>                    title: title,<br>                    textColor: textColor,<br>                    backgroundColor: backgroundColor<br>                )<br>            }<br><br>            // Compose view rendering<br>            var hostingVC: UIHostingController&lt;FullScreenInAppMessageView&gt;? = nil<br><br>            let view = FullScreenInAppMessageView(<br>                image: image,<br>                primaryButton: primaryStyle,<br>                secondaryButton: secondaryStyle,<br>                onPrimary: {<br>                    // Tell Firebase the message was tapped<br>                    let action = InAppMessagingAction(actionText: actionButton.buttonText, actionURL: actionURL)<br>                    displayDelegate.messageClicked?(message, with: action)<br><br>                    // Remove the message from screen<br>                    hostingVC?.view.removeFromSuperview()<br>                },<br>                onSecondary: {<br>                    // Notify Firebase about dismissal<br>                    displayDelegate.messageDismissed?(message, dismissType: .typeAuto)<br>                    hostingVC?.view.removeFromSuperview()<br>                }<br>            )<br><br>            // Embed our SwiftUI inside UIKit<br>            hostingVC = UIHostingController(rootView: view)<br>            hostingVC?.view.backgroundColor = .clear<br>            hostingVC?.view.frame = window.bounds<br>            if let finalView = hostingVC?.view {<br>                window.addSubview(finalView)<br>            }<br>        }<br>    }<br>}</pre><p><strong>✨ Summary of what’s happening:</strong></p><ul><li>We <strong>decode</strong> the message and its image.</li><li>We <strong>extract</strong> the button styles and handle optional secondary buttons using appData.</li><li>We <strong>wrap</strong> our SwiftUI layout (FullScreenInAppMessageView) into a UIHostingController.</li><li><strong>We notify Firebase when the user interacts with the message (tap or dismiss)</strong> — allowing the entire Firebase ecosystem to track impressions, clicks, and dismissals. This maintains powerful analytics, conversion tracking, and audience targeting — benefits we’d lose if we built our own in-app messaging system from scratch.</li></ul><p><strong>🔌 Step 4 — The Actual Integration</strong></p><p>After designing our custom renderer and the UI, the final step is telling Firebase to <strong>use our custom renderer instead of the default one</strong>. This is as simple as setting the messageDisplayComponent:</p><pre>InAppMessaging.inAppMessaging().messageDisplayComponent = NologyInAppMessageRenderer()</pre><p>Once this line runs — typically in your AppDelegate — Firebase In-App Messaging will call our displayMessage() method whenever a message is triggered, handing full control over to our custom layout.</p><p>This marks the completion of our iOS setup. Next up: Android — where things get a little messier 👀</p><h3><strong>Android Ain’t Easy: Crafting Custom FIAM with Compose</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vHiSGFYD5LEimtTUpi4y-w.png" /></figure><h3><strong>Setting Up Jetpack Compose: The First Brick in the Wall 🧱</strong></h3><p>Before diving into the custom renderer, we first needed to enable Jetpack Compose in our Flutter project’s native Android layer. This meant updating the build.gradle file with the proper buildFeatures, setting the kotlinCompilerExtensionVersion, and pulling in all the right dependencies.</p><pre>buildFeatures {<br>    compose true<br>}<br>composeOptions {<br>    kotlinCompilerExtensionVersion = &quot;1.4.8&quot;<br>}</pre><p>Then we added the essential Compose libraries:</p><pre>// Compose BOM<br>implementation platform(&quot;androidx.compose:compose-bom:2025.02.00&quot;)<br><br>// Core UI<br>implementation &quot;androidx.compose.ui:ui&quot;<br>implementation &quot;androidx.compose.ui:ui-tooling-preview&quot;<br>implementation &quot;androidx.compose.material3:material3&quot;<br><br>// Runtime<br>implementation &quot;androidx.activity:activity-compose:1.10.1&quot;<br><br>// For debugging previews<br>debugImplementation &quot;androidx.compose.ui:ui-tooling&quot;</pre><p>But here’s where things get interesting…</p><h4>🧨 <strong>Why version 1.4.8?</strong></h4><p>Because if you go any higher while using Kotlin 1.8.22 (which Flutter ships with), Compose will politely scream at you. We initially tried newer versions, only to be met with this charming message:</p><blockquote>“This version of the Compose Compiler requires Kotlin version 1.9.23 but you are using 1.8.22 which is not known to be compatible…”</blockquote><blockquote>Please consult the Compose-Kotlin compatibility map located at <a href="https://developer.android.com/jetpack/androidx/releases/compose-kotlin">https://developer.android.com/jetpack/androidx/releases/compose-kotlin</a> to choose a compatible version pair</blockquote><p>And then it hits you with the legendary line:</p><blockquote><strong>”…or suppressKotlinVersionCompatibilityCheck but don’t say I didn’t warn you!”</strong></blockquote><p>Yeah. Compose isn’t messing around 😅. So we locked it down to 1.4.8, which plays nicely with the Kotlin version Flutter currently ships.</p><p>Once everything compiled and ran successfully, we knew we were good to go. Next step? Replacing the default modal renderer with our own Compose-powered magic.</p><h4><strong>Replacing the Default: Building Our Custom In-App Renderer</strong></h4><p>Firebase tells us: <em>implement FirebaseInAppMessagingDisplay and register it.</em> That’s all. No examples, no docs for Compose. Just vibes.</p><p>So here’s how we started — first, create the renderer class:</p><p><strong>💬 Firebase In-App Messaging on Android — Fully Custom with Jetpack Compose</strong></p><p>Even though the official documentation for custom in-app messages on Android is… let’s say <em>minimal</em>, the core idea is simple:</p><p>1. <strong>Implement</strong> FirebaseInAppMessagingDisplay</p><p>2. <strong>Register</strong> your custom class with Firebase using:</p><pre>FirebaseInAppMessaging.getInstance().setMessageDisplayComponent(NologyInAppMessageDisplay(context))</pre><p>Let’s walk through the custom implementation we built — clean, robust, and fully integrated with your Compose UI.</p><h4><strong>1. Define Your Button Style</strong></h4><p>We start with a simple data class that holds the title and colors for both buttons:</p><pre>data class InAppButtonStyle(<br>    val title: String,<br>    val textColor: Color,<br>    val backgroundColor: Color<br>)</pre><p>This keeps our buttons clean and easy to reuse.</p><h4><strong>2. Compose the Message UI</strong></h4><p>Here’s our full-screen message layout built with Jetpack Compose:</p><p>• Background overlay ✅</p><p>• Image content with rounded corners ✅</p><p>• Primary and optional secondary buttons ✅</p><pre><br>import androidx.compose.foundation.Image<br>import androidx.compose.foundation.background<br>import androidx.compose.foundation.layout.*<br>import androidx.compose.foundation.shape.RoundedCornerShape<br>import androidx.compose.material3.Button<br>import androidx.compose.material3.Text<br>import androidx.compose.runtime.Composable<br>import androidx.compose.ui.Alignment<br>import androidx.compose.ui.Modifier<br>import androidx.compose.ui.draw.clip<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.graphics.ImageBitmap<br>import androidx.compose.ui.layout.ContentScale<br>import androidx.compose.ui.platform.LocalConfiguration<br>import androidx.compose.ui.unit.dp<br>import com.nologystore.nology.inAppMessage.helpers.InAppButtonStyle<br><br>@Composable<br>fun FullScreenInAppMessageView(<br>    image: ImageBitmap,<br>    primaryButton: InAppButtonStyle,<br>    secondaryButton: InAppButtonStyle? = null,<br>    onPrimary: () -&gt; Unit,<br>    onSecondary: () -&gt; Unit<br>) {<br>    val config = LocalConfiguration.current<br>    val width = config.screenWidthDp.dp - 48.dp<br>    val height = config.screenHeightDp.dp * 0.75f<br><br>    Box(<br>        modifier = Modifier<br>            .fillMaxSize()<br>            .background(Color.Black.copy(alpha = 0.5f))<br>    ) {<br>        Box(<br>            modifier = Modifier<br>                .width(width)<br>                .height(height)<br>                .align(Alignment.Center)<br>                .background(Color.White, shape = RoundedCornerShape(24.dp))<br>        ) {<br><br>            Image(<br>                bitmap = image,<br>                contentDescription = &quot;In App Image&quot;,<br>                contentScale = ContentScale.Crop,<br>                modifier = Modifier<br>                    .fillMaxSize()<br>                    .clip(RoundedCornerShape(24.dp))<br>            )<br><br>            Column(<br>                modifier = Modifier<br>                    .align(Alignment.BottomCenter)<br>                    .padding(bottom = 24.dp, start = 20.dp, end = 20.dp)<br>            ) {<br>                Row(<br>                    horizontalArrangement = Arrangement.spacedBy(16.dp),<br>                    modifier = Modifier.fillMaxWidth()<br>                ) {<br>                    if (secondaryButton != null) {<br>                        Button(<br>                            onClick = onSecondary,<br>                            modifier = Modifier.weight(1f),<br>                            colors = androidx.compose.material3.ButtonDefaults.buttonColors(<br>                                containerColor = secondaryButton.backgroundColor<br>                            )<br>                        ) {<br>                            Text(<br>                                text = secondaryButton.title,<br>                                color = secondaryButton.textColor<br>                            )<br>                        }<br>                    }<br><br>                    Button(<br>                        onClick = onPrimary,<br>                        modifier = Modifier.weight(1f),<br>                        colors = androidx.compose.material3.ButtonDefaults.buttonColors(<br>                            containerColor = primaryButton.backgroundColor<br>                        )<br>                    ) {<br>                        Text(<br>                            text = primaryButton.title,<br>                            color = primaryButton.textColor<br>                        )<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><blockquote><em>Note: We rely on LocalConfiguration to dynamically adapt width and height to screen size.</em></blockquote><h4><strong>🪟 Wrapping It in a DialogFragment</strong></h4><p>Jetpack Compose gives us a declarative way to build UI, but Firebase’s in-app messaging pipeline doesn’t support Compose natively. That’s where this wrapper comes in.</p><p>We built a custom InAppMessageDialog that:</p><p>• Hosts a ComposeView inside a classic DialogFragment</p><p>• Accepts a @Composable content block with a dismiss() callback</p><p>• Ensures proper lifecycle management using:</p><pre>setViewCompositionStrategy(<br>    ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)<br>)</pre><p>Here’s the implementation:</p><pre>class InAppMessageDialog(<br>    private val contentBuilder: @Composable (dismiss: () -&gt; Unit) -&gt; Unit<br>) : DialogFragment() {<br><br>override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {<br>     return Dialog(requireContext(), android.R.style.Theme_Translucent_NoTitleBar)<br>}<br><br>override fun onCreateView(<br>        inflater: LayoutInflater,<br>        container: ViewGroup?,<br>        savedInstanceState: Bundle?<br>    ): View = ComposeView(requireContext()).apply {<br>        setViewCompositionStrategy(<br>            ViewCompositionStrategy.DisposeOnLifecycleDestroyed(viewLifecycleOwner)<br>        )<br>        setContent {<br>            contentBuilder { dismissAllowingStateLoss() }<br>        }<br>    }<br><br>  override fun onStart() {<br>        super.onStart()<br>        dialog?.window?.setLayout(<br>            ViewGroup.LayoutParams.MATCH_PARENT,<br>            ViewGroup.LayoutParams.MATCH_PARENT<br>        )<br>    }<br>}</pre><p><strong>🤔 Why Not Just Use a Composable?</strong></p><p>You might be wondering: <em>Why not just display the view directly using Compose?</em></p><p>Well, here’s the deal:</p><p>• Firebase’s internal APIs expect a traditional <strong>Android view</strong> tree — not just a Composable function.</p><p>• We needed to <em>inject</em> our custom layout from outside Flutter into the current Activity, and <strong>Compose alone can’t manage full-window overlays</strong> easily without a Fragment or Dialog.</p><p><strong>• By using DialogFragment, we gain:</strong></p><p>• Full control over the <strong>window’s appearance</strong> (transparency, margins, fullscreen).</p><p>• A clean way to dismiss the message when the user interacts.</p><p>• Lifecycle awareness tied to the parent activity.</p><h4><strong>🧠 The Heart of the Custom FIAM: NologyInAppMessageDisplay</strong></h4><p>Now that our UI and dialog system are in place, it’s time to plug into the Firebase pipeline. This is where the NologyInAppMessageDisplay class comes in — the one that <strong>makes everything run</strong>.</p><p>Firebase requires you to implement the FirebaseInAppMessagingDisplay interface. That’s what lets us intercept the incoming message payload and render our custom view instead of the default.</p><pre>import android.content.Context<br>import android.content.Intent<br>import android.graphics.Bitmap<br>import android.graphics.BitmapFactory<br>import android.net.Uri<br>import android.os.Handler<br>import android.os.Looper<br>import android.util.Log<br>import androidx.compose.ui.graphics.Color<br>import androidx.compose.ui.graphics.asImageBitmap<br>import androidx.lifecycle.lifecycleScope<br>import com.google.firebase.inappmessaging.FirebaseInAppMessagingDisplay<br>import com.google.firebase.inappmessaging.FirebaseInAppMessagingDisplayCallbacks<br>import com.google.firebase.inappmessaging.model.InAppMessage<br>import com.google.firebase.inappmessaging.model.ModalMessage<br>import io.flutter.embedding.android.FlutterFragmentActivity<br>import kotlinx.coroutines.Dispatchers<br>import kotlinx.coroutines.launch<br>import kotlinx.coroutines.withContext<br>import java.net.HttpURLConnection<br>import java.net.URL<br>import com.nologystore.nology.inAppMessage.helpers.InAppButtonStyle<br><br><br>class NologyInAppMessageDisplay(private val context: Context) : FirebaseInAppMessagingDisplay {<br><br>    override fun displayMessage(<br>        inAppMessage: InAppMessage,<br>        callbacks: FirebaseInAppMessagingDisplayCallbacks<br>    ) {<br>        Log.d(&quot;FIAM&quot;, &quot;Context type: ${context::class.java.simpleName}&quot;)<br>        Handler(Looper.getMainLooper()).post {<br>            val activity = context as? FlutterFragmentActivity ?: return@post<br>            activity.lifecycleScope.launch {<br><br>                val modal = (inAppMessage as? ModalMessage).also {<br>                    Log.d(&quot;FIAM&quot;, &quot;Displaying message: ${it?.imageData?.imageUrl}&quot;)<br>                } ?: run {<br>                    Log.w(&quot;FIAM&quot;, &quot;Message is not a modal type.&quot;)<br>                    return@launch<br>                }<br><br>                val imageBitmap = modal.imageData?.bitmapData ?: run {<br>                    val imageUrl = modal.imageData?.imageUrl<br>                    if (imageUrl == null) {<br>                        Log.w(&quot;FIAM&quot;, &quot;No image found.&quot;)<br>                        return@launch<br>                    }<br>                    loadBitmapSuspend(imageUrl)?.also {<br>                        Log.d(&quot;FIAM&quot;, &quot;Bitmap loaded successfully&quot;)<br>                    } ?: run {<br>                        Log.w(&quot;FIAM&quot;, &quot;❌ Failed to load image.&quot;)<br>                        return@launch<br>                    }<br>                }<br><br>                val primaryAction = modal.action ?: run {<br>                    Log.w(&quot;FIAM&quot;, &quot;No primary action found.&quot;)<br>                    return@launch<br>                }<br>                val url = primaryAction.actionUrl ?: run {<br>                    Log.w(&quot;FIAM&quot;, &quot;No URL found.&quot;)<br>                    return@launch<br>                }<br><br>                val button = primaryAction.button ?: run {<br>                    Log.w(&quot;FIAM&quot;, &quot;No button found.&quot;)<br>                    return@launch<br>                }<br><br>                val buttonText = button.text.text ?: run {<br>                    Log.w(&quot;FIAM&quot;, &quot;No button text found.&quot;)<br>                    return@launch<br>                }<br><br>                val primaryButton = InAppButtonStyle(<br>                    title = buttonText,<br>                    textColor = hexToColor(button.text.hexColor),<br>                    backgroundColor = hexToColor(button.buttonHexColor)<br>                )<br><br>                val secondaryButton = inAppMessage.data?.let {<br>                    val title = it[&quot;secondaryTitle&quot;]<br>                    val textColorHex = it[&quot;secondaryTextColor&quot;]<br>                    val backgroundHex = it[&quot;secondaryBackgroundColor&quot;]<br>                    if (title != null &amp;&amp; textColorHex != null &amp;&amp; backgroundHex != null) {<br>                        InAppButtonStyle(<br>                            title = title,<br>                            textColor = hexToColor(textColorHex),<br>                            backgroundColor = hexToColor(backgroundHex)<br>                        )<br>                    } else null<br>                }<br><br>                val dialog = InAppMessageDialog { dismiss -&gt;<br>                    FullScreenInAppMessageView(<br>                        image = imageBitmap.asImageBitmap(),<br>                        primaryButton = primaryButton,<br>                        secondaryButton = secondaryButton,<br>                        onPrimary = {<br>                            callbacks.messageClicked(primaryAction)<br>                            val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))<br>                            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)<br>                            context.startActivity(intent)<br>                            dismiss()<br>                        },<br>                        onSecondary = {<br>                            secondaryButton?.let { _ -&gt;<br>                                callbacks.messageDismissed(FirebaseInAppMessagingDisplayCallbacks.InAppMessagingDismissType.CLICK)<br>                            }<br>                            dismiss()<br>                        }<br>                    )<br>                }<br>                dialog.show(activity.supportFragmentManager, &quot;FIAM&quot;)<br>            }<br>        }<br>    }<br><br>    private fun hexToColor(hex: String): Color = try {<br>        Color(android.graphics.Color.parseColor(hex))<br>    } catch (e: Exception) {<br>        Color.Gray<br>    }<br><br>    private suspend fun loadBitmapSuspend(url: String): Bitmap? = withContext(Dispatchers.IO) {<br>        try {<br>            Log.d(&quot;FIAM&quot;, &quot;Loading image from URL: $url&quot;)<br>            val connection = URL(url).openConnection() as HttpURLConnection<br>            connection.doInput = true<br>            connection.connect()<br>            BitmapFactory.decodeStream(connection.inputStream)<br>        } catch (e: Exception) {<br>            null<br>        }<br>    }<br>}<br><br></pre><p><strong>🔍 What This Class Does</strong></p><p>Let’s break it down simply:</p><p>• <strong>Confirms message type:</strong> Only supports ModalMessage (you can extend this to other types like Banner, Card, or ImageOnly if needed).</p><p>• <strong>Loads remote image:</strong> Either from cached bitmapData or fetches via URL.</p><p>• <strong>Extracts button styles:</strong> Using custom colors and labels (including support for secondary buttons via appData).</p><p>• <strong>Wraps UI in a DialogFragment:</strong> Displays the Composable view we built earlier.</p><p>• <strong>Handles actions:</strong> Launches deep links via Intent and notifies Firebase about interactions using:</p><pre>callbacks.messageClicked(...)<br>callbacks.messageDismissed(...)</pre><p>This is how Firebase can <strong>track user behavior</strong> and give you metrics inside the Firebase Console — <strong>a big reason we chose this approach instead of building our own messaging service.</strong></p><h3><strong>Platform Differences: iOS vs Android</strong></h3><p>While building a cross-platform custom layout for Firebase In-App Messaging, we encountered a few key differences between the platforms that developers should be aware of.</p><h3><strong>Image Handling</strong></h3><p><strong>iOS — Raw Image Data Ready to Use</strong></p><ul><li>Messages come with imageRawData, ready to be passed directly into a UIImage.</li><li>No need for an additional network request.</li></ul><pre>let image = UIImage(data: imageRawData)</pre><p><strong>Android — Manual Image Download Required</strong></p><ul><li>Often only the imageUrl is provided.</li><li>You must manually download and decode the image to a Bitmap.</li></ul><pre>val bitmap = modal.imageData?.bitmapData ?: loadBitmapSuspend(imageUrl)</pre><blockquote><em>⚠️ Not documented clearly in Firebase’s official docs — we found this via real debugging.</em></blockquote><h4><strong>🔗 Deep Linking</strong></h4><p><strong>iOS — Firebase Handles It for You</strong></p><ul><li>Firebase automatically opens deep links via Safari or your app’s universal links.</li><li>No need to manually handle or trigger anything.</li></ul><pre>displayDelegate.messageClicked?(message, with: action)</pre><p><strong>Android — Manual Intent Required</strong></p><ul><li>Firebase doesn’t automatically launch the deep link.</li><li>You need to create and start an Intent manually for Intent.ACTION_VIEW.</li></ul><pre>  val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))<br>  intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP)<br>  context.startActivity(intent)</pre><blockquote><em>🧠 If you forget this, your deep link just won’t open — and no error will be shown!</em></blockquote><h4><strong>How to Test Custom In-App Messages</strong></h4><p>Testing Firebase In-App Messaging (FIAM) isn’t always straightforward — but it’s critical to get your custom UI working correctly across platforms.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HnEmIDvI37WWYiIZgs8foQ.png" /></figure><p>Luckily, Firebase provides a way to test campaigns instantly using a <strong>test device setup</strong> — here’s how it works:</p><h4><strong>Step 1: Get Your Firebase Installation ID (FID)</strong></h4><p>To send test messages, Firebase needs your device’s unique <strong>Installation ID (FID)</strong>.</p><p><strong>On Android:</strong></p><p>Run your app and check the logs for this line:</p><pre>I/FIAM.Headless: Starting InAppMessaging runtime with Installation ID &lt;YOUR_INSTALLATION_ID&gt;</pre><p><strong>On iOS:</strong></p><p>Enable debug mode in Xcode:</p><p>1. Go to Product &gt; Scheme &gt; Edit Scheme…</p><p>2. In the <strong>Arguments</strong> tab, add:</p><pre>-FIRDebugEnabled</pre><p>3. Run the app and look for:</p><pre>[Firebase/InAppMessaging][I-IAM180017] Starting InAppMessaging runtime with Firebase Installation ID &lt;YOUR_INSTALLATION_ID&gt;</pre><h4><strong>Step 2: Send a Test Message</strong></h4><p>Before releasing your custom in-app message layout to real users, it’s essential to test it properly. Firebase makes this possible through <strong>Test Devices</strong>, which allow you to trigger messages instantly — skipping the 24-hour caching delay.</p><p>Here’s your updated step-by-step guide</p><p><strong>1- Choose the Right Layout</strong></p><p>When creating your Firebase In-App Messaging campaign:</p><ul><li>Choose <strong>Modal</strong> as the message layout — it’s the <strong>only layout</strong> currently supported by our custom renderer.</li><li>Make sure to <strong>ignore other layouts</strong> like Card, Banner, or Image-Only — they won’t trigger your custom view.</li></ul><p><strong>2- Add Custom Data for Secondary Button</strong></p><p>In <strong>Step 5: Additional options</strong>, provide the following <strong>Custom data</strong>:</p><pre>secondaryTitle: SKIP<br>secondaryTextColor: #000000<br>secondaryBackgroundColor: #C9C9C9</pre><p>This will ensure the secondary button appears correctly with the desired text and styling. Without it, the button won’t render.</p><p><strong>3. Hit “Test” With Your Device’s ID</strong></p><ul><li>Paste the <strong>FID</strong> you copied in Step 1.</li><li>Click <strong>Test</strong>.</li><li>Reopen your app — the in-app message should appear immediately.</li></ul><h3><strong>🔗 About Deep Links?</strong></h3><p>If you’re wondering <strong>how we handle deep links</strong> with this setup — well, that’s a whole story on its own. 🔥</p><p>From configuring assetlinks.json on Android to setting up apple-app-site-association for Universal Links on iOS, and designing a <strong>smart Flutter routing system</strong> that matches web paths (with support for path params and query strings)… there’s <em>a lot</em> to cover.</p><p>I’ll prepare a <strong>dedicated article</strong> covering every small detail:</p><ul><li>Setting up app links and Universal Links</li><li>Domain verification</li><li>Required files for each platform</li><li>Mapping deep links to Flutter routes</li></ul><p>If you’re interested, just drop a comment — I’ll prioritize it and make sure it’s packed with practical examples and real use cases!</p><h3><strong>Wrapping Up</strong></h3><p>Building custom layouts for <strong>Firebase In-App Messaging</strong> isn’t just about styling — it’s about <strong>creating immersive, native, analytics-driven experiences</strong> that match your app’s personality and performance goals. By leveraging <strong>SwiftUI</strong> and <strong>Jetpack Compose</strong>, we crafted a fully branded, dynamic in-app message flow — and did it without compromising the Firebase ecosystem benefits.</p><p>From deep link support to analytics tracking, we stayed close to Firebase’s native protocols while still delivering a UI that <em>feels ours</em>.</p><h3><strong>Who’s behind this?</strong></h3><p>I’m <strong>Salah Nahed</strong>, a Flutter &amp; mobile craftsman with a love for building polished, scalable solutions across platforms. I’ve worked across startups and scaleups — crafting packages like <a href="https://github.com/onestudio-co/flutter-bond">bond</a> and building systems that blend UX with technical elegance.</p><p><strong>I’m currently open to:</strong></p><ul><li>Freelance consulting gigs</li><li>Architecture or implementation support</li><li>Collaborations with product teams</li></ul><p>📩 <strong>Let’s talk:</strong></p><p>Got a feature to ship? A refactor to plan? Or a dream to build?</p><p>📩 <a href="https://www.linkedin.com/in/salah-amassi-a73250135/">Connect with me on LinkedIn</a></p><p><strong>Follow my tech journey</strong></p><p>🐦 Twitter/X: <a href="https://x.com/salahamassi">@salahamassi</a></p><p>📸 Instagram: <a href="https://instagram.com/salahamassi">@salahamassi</a></p><p>🐙 GitHub: <a href="https://github.com/salahamassi">salahamassi</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2b7875d8a7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Protocol Magic: Building a Beautiful, Reusable Option Selection System]]></title>
            <link>https://medium.com/@salahamassi/swift-protocol-magic-building-a-beautiful-reusable-option-selection-system-bcb76adead7c?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcb76adead7c</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol-oriented]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Sun, 30 Mar 2025 22:00:12 GMT</pubDate>
            <atom:updated>2025-04-01T11:34:32.370Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*i5BxfXF6V--22-jA.png" /></figure><h3>🎨 Paragraph 1: The Artist’s Pain</h3><blockquote><em>“This is not just code. This is me painting on a blank canvas.”</em></blockquote><p>I come from Gaza — a place where electricity is a luxury and quiet nights are often interrupted by warplanes, not whispers. And yet, in the middle of this chaos, I found peace in writing code. Not just any code — but code that feels like art. Clean. Modular. Elegant.</p><p>I still remember the first time I fell in love with programming. It wasn’t just the logic, the problem-solving, or the satisfaction of building something from nothing. It was the way code flowed under my fingers, like a brush on canvas. A silent, invisible dance between what I imagine and what becomes real. I wasn’t writing software. I was composing symphonies, designing cities, crafting worlds.</p><p>When I built the Winch options system, I didn’t just want it to work — I wanted it to feel alive, composable, magical. I wanted every line of code to be an expression of intent, every protocol to feel like a piece of poetry. This story is the journey of building that. Of how I turned chaos into clarity. Of how I wrote my favorite piece of code yet.</p><h3>🌱 Paragraph 2: The Root of Repetition</h3><p>In a logistics app like Winch, we have tons of dropdowns, multi-selects, and filters: cities, regions, vehicle types, services, roles, branches… and the list goes on.</p><p>Initially, each screen hardcoded its options UI. The same boilerplate repeated again and again:</p><ul><li>Fetch data from an endpoint.</li><li>Transform it into a UI-friendly model.</li><li>Present it in a table.</li><li>Handle selection and formatting.</li></ul><p>It was error-prone. It was boring. And most of all — it was ugly.</p><p>So I paused. I stared at the patterns. And I asked myself: what would a painter do?</p><h3>🚀 Paragraph 3: A Vision of Harmony</h3><p>I paused. I thought: <em>What if I never had to write the logic to load cities again?</em> What if the structure of filterable data — be it from API or static JSON — could be abstracted into a single, elegant protocol?</p><p>I wanted something composable. Beautiful. Something that could give a junior developer superpowers, and make a senior developer smile. It had to be flexible enough to support API queries, yet simple enough to handle a static array.</p><p>I wanted a world where I could write:</p><pre>createOptionsViewController(<br>    type: Cities.self,<br>    view: citySelectionView,<br>    keyPath: \.selectedCities<br>)</pre><p>…and everything would just work.</p><p>No repetitive fetching logic. No custom transformers. No boilerplate UI config.</p><p>Just types. Just intent. Just beauty.</p><p>So I opened Xcode, created a new file, and named it: MenuType.swift.</p><h3>🛠️ Paragraph 4: The Craft — One Protocol to Rule Them All</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e03xr_MCW7iaoVlfBRIqLw.png" /></figure><p>This was the beating heart of the system:</p><h3>The Protocol:</h3><pre>public protocol MenuType {<br>    init()<br>    typealias MenuLoaderCompletion = (Result&lt;[OptionModel], WinchError&gt;) -&gt; Void<br>    var path: String { get }<br>    var staticData: [OptionModel]? { get }<br>    func allCases(query: [String: String], completion: @escaping MenuLoaderCompletion)<br>    associatedtype Model: SwiftyModelData<br>    func provideCustomType() -&gt; Model.Type<br>    func provideCustomTypeMaper(_ data: [Model]) -&gt; [OptionModel]<br>}</pre><p>Each property and function had a purpose:</p><ul><li>path: The API endpoint.</li><li>staticData: Optional fallback data.</li><li>allCases(query:): Unified entry point for loading data.</li><li>provideCustomType: Defines the decoding target.</li><li>provideCustomTypeMaper: Lets you transform your decoded model into UI-friendly OptionModels.</li></ul><h3>The Default Implementation:</h3><pre>public extension MenuType {<br><br>  var staticData: [OptionModel]? { nil }<br><br>    func provideCustomType() -&gt; OptionModel.Type {<br>          OptionModel.self<br>    }<br><br>   func provideCustomTypeMaper(_ data: [OptionModel]) -&gt; [OptionModel] {<br>        data<br>    }<br><br>   func allCases(query: [String: String], completion: @escaping MenuLoaderCompletion) {<br>        loadData(query: query, completion: completion)<br>    }<br><br>    private func loadData(query: [String: String], completion: @escaping MenuLoaderCompletion) {<br>        if let staticData = staticData {<br>            completion(.success(staticData))<br>            return<br>        }<br>        var fullPath = path<br>        if !query.isEmpty {<br>            let queryString = query.map { &quot;\($0.key)=\($0.value)&quot; }.joined(separator: &quot;&amp;&quot;)<br>            fullPath += &quot;?\(queryString)&quot;<br>        }<br>        let networkService = NetworkApiDataSourceService(<br>            path: fullPath,<br>            domain: WinchConfiguration.shared.apiURL,<br>            method: &quot;GET&quot;,<br>            params: [:],<br>            arrayRequest: true<br>        )<br>        let appDataSource = WinchConfiguration.shared.appDataSource<br>        appDataSource.perform(service: networkService, provideCustomType()) { result in<br>            switch result {<br>            case .array(let data):<br>                let options = provideCustomTypeMaper(data.data)<br>                completion(.success(options))<br>            case .failure(let error):<br>                completion(.failure(error.convertToWinchError()))<br>            default: break<br>            }<br>        }<br>    }<br>}</pre><p>This default logic was a revelation. Suddenly, 80% of my filters only needed to implement a path.</p><p>But the real power came when I needed something <em>custom</em>.</p><h3>🧱 OptionModel &amp; SelectableModel</h3><p>These two simple models hold the entire selection experience together:</p><pre>public struct OptionModel: Equatable, PresentableModel, Comparable {<br>    public let id: String<br>    public let name: String<br>    public let icon: String?<br>    public let children: [OptionModel]?<br>    public let additionalData: [String: Any]?<br><br>    public init(id: String, name: String, icon: String? = nil, children: [OptionModel]? = nil, additionalData: [String: Any]? = nil) {<br>        self.id = id<br>        self.name = name<br>        self.icon = icon<br>        self.children = children<br>        self.additionalData = additionalData<br>    }<br>    public var idValue: String { id }<br>    public var presentableValue: String { name }<br><br>    public static func &lt; (lhs: OptionModel, rhs: OptionModel) -&gt; Bool {<br>        if let left = Int(lhs.id), let right = Int(rhs.id) {<br>            return left &lt; right<br>        }<br>        return lhs.id &lt; rhs.id<br>    }<br>}<br><br>struct SelectableModel&lt;T&gt; {<br>    let model: T<br>    var selected: Bool<br>    var children: [SelectableModel&lt;T&gt;]?<br>}</pre><ul><li>OptionModel represents a selectable item. It can hold an icon, nested children, and extra metadata (additionalData).</li><li>SelectableModel wraps any T, tracks its selection state, and optionally supports children (for grouped filters).</li></ul><p>This duo powers the entire OptionsViewController rendering and sync logic.</p><h3>🧠 Real-World Customization: Cities.swift</h3><p>Some use cases need more than the default — more structure, more transformation. Let me show you a real example: the Cities filter, where I needed to display cities grouped by their region.</p><pre>struct Cities: MenuType {<br>  public init() {}<br><br> var path: String {<br>     &quot;cities&quot;<br> }<br><br> func provideCustomType() -&gt; Cities.City.Type {<br>      City.self<br> }<br>  <br> func provideCustomTypeMaper(_ data: [City]) -&gt; [OptionModel] {<br>        let validCities = data.filter {<br>            $0.region.id != 0 &amp;&amp; !$0.region.name.isEmpty<br>        }<br>        let grouped = Dictionary(grouping: validCities, by: { $0.region })<br>        return grouped.map { region, cities in<br>            OptionModel(<br>                id: &quot;\(region.id)&quot;,<br>                name: region.name,<br>                children: cities.map {<br>                    OptionModel(<br>                        id: &quot;\($0.id)&quot;,<br>                        name: $0.name,<br>                        additionalData: $0.toJSON().dictionaryObject<br>                    )<br>                },<br>                additionalData: [<br>                    &quot;region_id&quot;: region.id,<br>                    &quot;region_name&quot;: region.name<br>                ]<br>            )<br>        }.sorted()<br>    }<br><br>     struct City {<br>        let id: Int<br>        let name: String<br>        let region: Region<br>        struct Region: Hashable {<br>            let id: Int<br>            let name: String<br>        }<br>    }<br><br>  }<br><br>  extension Cities.City: SwiftyModelData {<br>    init(json: JSON) {<br>        id = json[&quot;id&quot;].intValue<br>        name = json[&quot;name&quot;].stringValue<br>        region = Region(<br>            id: json[&quot;region&quot;][&quot;id&quot;].intValue,<br>            name: json[&quot;region&quot;][&quot;name&quot;].stringValue<br>        )<br>    }<br>    func toJSON() -&gt; JSON {<br>        JSON([<br>            &quot;id&quot;: id,<br>            &quot;name&quot;: name,<br>            &quot;region&quot;: [<br>                &quot;id&quot;: region.id,<br>                &quot;name&quot;: region.name<br>            ]<br>        ])<br>    }<br>}</pre><p>This is where the protocol shines. The network logic? Already handled. The query injection? Already handled. The decoding? Check. All I had to do was focus on <em>how I want to shape the data</em> — and thanks to provideCustomType and provideCustomTypeMaper, I did exactly that.</p><p>Clean. Elegant. Reusable.</p><h3>🎬 Paragraph 6 — BaseOptionsConfigurable: One Interface, Two Destinies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3rX_51bSQpa3jnKV.png" /></figure><p>Designing reusable UI logic isn’t just about making things work — it’s about making them feel inevitable, like the pieces were always meant to fit this way. That’s exactly what BaseOptionsConfigurable does. It acts like the unsung hero at the center of our architecture — abstract enough to be reused, yet powerful enough to orchestrate everything from visual rendering to syncing logic between views and controllers.</p><p>Let’s break it down.</p><pre>@MainActor<br>protocol BaseOptionsConfigurable: UIResponder {<br><br> var optionsBottomSheet: OptionsBottomSheetView { get }<br><br>  func render&lt;T: MenuType&gt;(<br>        _ values: [OptionModel]?,<br>        to view: WinchItemView,<br>        and controller: OptionsViewController&lt;T&gt;,<br>        formatter: (([OptionModel]) -&gt; String)?<br>    )<br>}</pre><p>This protocol isn’t meant to be used directly — it’s a bridge. The foundation for its two children:</p><ul><li>OptionsConfigurable: stores values locally until submission.</li><li>APIOptionsConfigurable: sends values immediately to the backend.</li></ul><p>They both need to show a bottom sheet, both need to render values in UI, and both need to sync selections between a WinchItemView and the internal controller. So instead of repeating all that boilerplate, we put it here. Once. Forever.</p><h3>🧪 The Render Flow (Extension Breakdown)</h3><pre>extension BaseOptionsConfigurable {<br><br>   func render&lt;T: MenuType&gt;(<br>        _ values: [OptionModel]?,<br>        to view: WinchItemView,<br>        and controller: OptionsViewController&lt;T&gt;,<br>        formatter: (([OptionModel]) -&gt; String)? = nil<br>    ) {<br>        let newValues = values ?? []<br>        controller.syncSelectedValues(newValues)<br>        renderItemValue(newValues, to: view, formatter: formatter)<br>    }<br><br>    func renderItemValue(<br>        _ values: [OptionModel],<br>        to view: WinchItemView,<br>        formatter: (([OptionModel]) -&gt; String)? = nil<br>    ) {<br>        guard !values.isEmpty else {<br>            view.value = nil<br>            return<br>        }<br>        let formattedValue = formatter?(values) ?? {<br>            let count = values.count<br>            let moreKeyword = &quot;keyword.more&quot;.localized<br>            return count == 1<br>                ? values.first!.name<br>                : &quot;\(values.first!.name) +\(count - 1) \(moreKeyword)&quot;<br>        }()<br>         view.borderColor = .deActivatedBorderColor<br>        view.value = formattedValue<br>    }<br>}</pre><h3>🧠 Let’s Understand the Parameters</h3><ul><li>values: the selected options, usually returned from the controller or from initial defaults.</li><li>view: the UI component (WinchItemView) that shows the current selection.</li><li>controller: an OptionsViewController, which manages selectable data and updates.</li><li>formatter: an optional closure that lets you override the text shown in the UI.</li></ul><p>If no formatter is provided, we gracefully fall back to:</p><ul><li>Show the first option name if there’s only one.</li><li>Or show &quot;City A +2 more&quot; if you selected three.</li></ul><p>This small detail is what makes the UI feel human.</p><p>In sum, BaseOptionsConfigurable gave us a canvas. A way to inject logic into any screen — whether it’s API-backed or form-bound — and let the screen render, sync, and behave like it belongs in a bigger system.</p><p>Because it does.</p><h3>⚙️ Paragraph 7: Configurable Power — Local vs. Live</h3><p>So far, we had the MenuType to load options — but what happens after that?</p><p>When a user taps on a WinchItemView, we need to show the available options and handle what happens after selection. Should we save the data locally? Should we call the API immediately? That&#39;s where the OptionsConfigurable and APIOptionsConfigurable protocols come in.</p><p>They are two distinct philosophies for managing user selections:</p><p>FeatureOptionsConfigurable (FormData)APIOptionsConfigurable (API)Where values are stored?In local formDataImmediately sent to APIWhen API is called?On final form submissionInstantly after user clicks Action buttonError handling?None neededShows alert and prevents sheet from closingBottom Sheet BehaviorAlways closes after selectionCloses only if API call succeeds</p><p>They are two distinct philosophies for managing user selections:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zoROBrB7xwgI8Jwd.png" /></figure><h3>🧩 OptionsConfigurable</h3><p>Designed for scenarios like forms or delayed submissions. You store user selections locally, then send them later.</p><h3>Protocol Definition:</h3><pre>@MainActor<br>public protocol OptionsConfigurable: BaseOptionsConfigurable {<br><br> associatedtype FormData<br><br> var formData: FormData { get set }<br><br> func createOptionsViewController&lt;T: MenuType&gt;(<br>        type: T.Type,<br>        view: WinchItemView,<br>        defaultValues: [OptionModel]?,<br>        keyPath: WritableKeyPath&lt;FormData, [OptionModel]?&gt;,<br>        didSelectValues: ValueCallBack&lt;[OptionModel]?&gt;?,<br>        optionsConfig: OptionsViewConfig<br>    ) -&gt; OptionsViewController&lt;T&gt;<br>}</pre><h3>Default Implementation:</h3><pre>public extension OptionsConfigurable {<br>    func createOptionsViewController&lt;T: MenuType&gt;(<br>        type: T.Type,<br>        view: WinchItemView,<br>        defaultValues: [OptionModel]? = nil,<br>        keyPath: WritableKeyPath&lt;FormData, [OptionModel]?&gt;,<br>        didSelectValues: ValueCallBack&lt;[OptionModel]?&gt;? = nil,<br>        optionsConfig: OptionsViewConfig = .default<br>    ) -&gt; OptionsViewController&lt;T&gt; {<br>        let viewController = OptionsViewController&lt;T&gt;(<br>            didSubmitSelectedFilters: { [weak self] selectedOptions in<br>                guard let self = self else { return }<br>                didSelectValues?(selectedOptions)<br>                self.renderItemValue(selectedOptions, to: view, formatter: optionsConfig.formatter)<br>                self.formData[keyPath: keyPath] = selectedOptions<br>                self.optionsBottomSheet.hide()<br>            },<br>            defaultFilters: defaultValues,<br>            hideNavigationBar: true,<br>            singleSelectionMode: false,<br>            enableSearch: optionsConfig.enableSearch,<br>            actionButtonTitle: optionsConfig.actionButtonTitle<br>        )<br>        viewController.title = view.title<br><br>        if let defaultValues = defaultValues {<br>            formData[keyPath: keyPath] = defaultValues<br>            render(defaultValues, to: view, and: viewController, formatter: optionsConfig.formatter)<br>        }<br><br>        view.actionButtonTapped = { [weak self] in<br>            self?.optionsBottomSheet.setOptionViewController(viewController, title: view.title ?? &quot;&quot;)<br>            self?.optionsBottomSheet.show()<br>        }<br>     return viewController<br>    }<br>}</pre><h3>Parameter Breakdown:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*u4LoNSZJkehjXWMT.png" /></figure><h3>🧰 OptionsViewConfig: The Behavior Controller</h3><p>The OptionsViewConfig struct allows you to tweak the behavior of the options view — from enabling search to customizing the save button, and even how selected values appear in the UI.</p><h3>The Code:</h3><pre>public struct OptionsViewConfig {<br><br>    public var enableSearch: Bool<br>    public var actionButtonTitle: String?<br>    public var formatter: (([OptionModel]) -&gt; String)?  <br><br>    public init(<br>        enableSearch: Bool = true,<br>        actionButtonTitle: String? = nil,<br>        formatter: (([OptionModel]) -&gt; String)? = nil<br>    ) {<br>        self.enableSearch = enableSearch<br>        self.actionButtonTitle = actionButtonTitle<br>        self.formatter = formatter<br>    }<br><br>    public static var `default`: OptionsViewConfig {<br>        OptionsViewConfig()<br>    }<br>}</pre><h3>What Each Property Does:</h3><ul><li>enableSearch: Turns on the search bar in the bottom sheet.</li><li>actionButtonTitle: Allows you to change the text of the save button.</li><li>formatter: Lets you customize how selected values are rendered in the UI (e.g. “Selected: 3 Items”).</li></ul><h3>Example:</h3><pre>OptionsViewConfig(<br>    enableSearch: true,<br>    actionButtonTitle: &quot;CONTINUE&quot;,<br>    formatter: { options in &quot;Selected: \(options.count)&quot; }<br>)</pre><p>This makes your bottom sheet more expressive, localized, and fine-tuned for each use case.</p><h3>⚡️ APIOptionsConfigurable</h3><p>Designed for real-time updates. As soon as the user picks something and taps the action button, we hit the API and only close the sheet if the request is successful.</p><h3>Protocol Definition:</h3><pre>@MainActor<br>public protocol APIOptionsConfigurable: BaseOptionsConfigurable {<br><br>var appDataSource: WinchDataSource { get set }<br><br>func createOptionsViewController&lt;T: MenuType, R: SwiftyModelData&gt;(<br>        type: T.Type,<br>        view: WinchItemView,<br>        defaultValues: [OptionModel]?,<br>        apiPath: String,<br>        apiKey: String,<br>        cachePath: String?,<br>        responseType: R.Type,<br>        didSelectValues: ValueCallBack&lt;[OptionModel]?&gt;?,<br>        optionsConfig: OptionsViewConfig<br>    ) -&gt; OptionsViewController&lt;T&gt;<br>}</pre><h3>Default Implementation:</h3><pre>public extension APIOptionsConfigurable {<br><br>   func createOptionsViewController&lt;T: MenuType, R: SwiftyModelData&gt;(<br>        type: T.Type,<br>        view: WinchItemView,<br>        defaultValues: [OptionModel]? = nil,<br>        apiPath: String,<br>        apiKey: String,<br>        cachePath: String? = nil,<br>        responseType: R.Type,<br>        didSelectValues: ValueCallBack&lt;[OptionModel]?&gt;? = nil,<br>        optionsConfig: OptionsViewConfig = .default<br>    ) -&gt; OptionsViewController&lt;T&gt; {<br>        let viewController = OptionsViewController&lt;T&gt;(<br>            didSubmitSelectedFilters: { [weak self] selectedOptions in<br>                guard let self = self else { return }<br>                didSelectValues?(selectedOptions)<br>                Task {<br>                    let data = await self.submitSelectedFilter(<br>                        selectedOptions: selectedOptions,<br>                        apiPath: apiPath,<br>                        apiKey: apiKey,<br>                        cachePath: cachePath,<br>                        responseType: responseType<br>                    )<br>                    if let _ = data {<br>                        self.renderItemValue(selectedOptions, to: view, formatter: optionsConfig.formatter)<br>                        self.optionsBottomSheet.hide()<br>                    }<br>                }<br>            },<br>            defaultFilters: defaultValues,<br>            hideNavigationBar: true,<br>            singleSelectionMode: false,<br>            enableSearch: optionsConfig.enableSearch,<br>            actionButtonTitle: optionsConfig.actionButtonTitle<br>        )<br>        viewController.title = view.title<br>        if let defaultValues = defaultValues {<br>            render(defaultValues, to: view, and: viewController, formatter: optionsConfig.formatter)<br>        }<br>         view.actionButtonTapped = { [weak self] in<br>            self?.optionsBottomSheet.setOptionViewController(viewController, title: view.title ?? &quot;&quot;)<br>            self?.optionsBottomSheet.show()<br>        }<br>      return viewController<br>    }<br>}</pre><h3>Parameter Breakdown:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*uEklB7jpn2gqeciO.png" /></figure><h3>👇 Example: AddBusinessUserViewController</h3><pre>class AddBusinessUserViewController: NibViewController, OptionsConfigurable {<br><br>    struct FormData {<br>        var branches: [OptionModel]?<br>        var role: OptionModel?<br>    }<br><br>    var formData = FormData()<br>    var optionsBottomSheet = OptionsBottomSheetView()<br><br>    @IBOutlet weak var branchesWinchItemView: WinchItemView!<br>    @IBOutlet weak var roleWinchItemView: WinchItemView!<br><br>    private lazy var branchesViewController: OptionsViewController&lt;Branches&gt; = {<br>        createOptionsViewController(<br>            type: Branches.self,<br>            view: branchesWinchItemView,<br>            keyPath: \.branches<br>        )<br>    }()<br><br>    private lazy var rolesViewController: OptionsViewController&lt;Roles&gt; = {<br>        createOptionViewController(<br>            type: Roles.self,<br>            view: roleWinchItemView,<br>            keyPath: \FormData.role<br>        )<br>    }()<br><br>   override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Setup is handled by protocols — clean and minimal!<br>    }<br>}</pre><h3>🔄 Switching Between the Two</h3><p>Want to convert a screen from local to live or vice versa? It’s just a matter of changing the protocol you conform to:</p><ul><li>From:</li></ul><pre>class MyViewController: NibViewController, OptionsConfigurable { ... }</pre><ul><li>To:</li></ul><pre>class MyViewController: NibViewController, APIOptionsConfigurable { ... }</pre><p>With minimal changes to your setup logic — just provide apiPath, apiKey, and responseType, and you&#39;re good to go.</p><p>That’s how flexible and modular the architecture is. 💡</p><h3>🪟 Paragraph 8: The Interface-OptionsViewController</h3><p>At the core of this orchestration is the OptionsViewController&lt;T&gt;. This is the UI controller that renders the selectable items in a bottom sheet.</p><p>It’s generic over any MenuType — meaning it works for Roles, Cities, Branches, and anything else that conforms to our contract.</p><h3>Core Responsibilities</h3><ul><li>Render hierarchical or flat options.</li><li>Support multi or single selection.</li><li>Handle search and filtering.</li><li>Display an empty view if needed.</li><li>Maintain selected state and sync with UI.</li><li>Call a completion handler with selected values.</li></ul><h3>Key Properties</h3><pre>public class OptionsViewController&lt;T: MenuType&gt;: NibViewController {<br>    var originalFilters = [SelectableMenuItem]()<br>    var filters = [SelectableMenuItem]()<br>    var selectedFilters: [OptionModel]?<br>    private let singleSelectionMode: Bool<br>    public let didSubmitSelectedFilters: (([OptionModel]) -&gt; Void)<br>    public let hideNavigationBar: Bool<br>    public let enableSearch: Bool<br>    public let actionButtonTitle: String?<br>    ...<br>}</pre><p>Each of these properties supports a concern:</p><ul><li>originalFilters retains a reference to the unfiltered list.</li><li>filters is the currently displayed list (can change due to search).</li><li>selectedFilters tracks selected items.</li><li>singleSelectionMode toggles between radio-style and checkbox-style.</li><li>didSubmitSelectedFilters is our callback to the outside world.</li><li>actionButtonTitle customizes the save button text.</li></ul><p>You pass the config from OptionsViewConfig, and this controller does all the work of:</p><ul><li>Querying the MenuType</li><li>Rendering results</li><li>Handling taps</li><li>Updating models</li></ul><p>It’s long. It’s powerful. It took weeks of tweaking.</p><p>But this story isn’t about UIKit. This is a Swift protocol love letter.</p><p>So we won’t show the full controller code here.</p><blockquote><em>If you’re curious to explore the full implementation of OptionsViewController_, feel free to reach out — I’m more than happy to share and </em><a href="https://www.linkedin.com/in/salah-amassi-a73250135/"><em>connect</em></a><em>._</em></blockquote><h3>📘 Paragraph 9: What We Can Improve</h3><p>Even though this architecture has proven itself in real products, there’s always room to evolve. Here are a few areas I believe can make it even more powerful:</p><ul><li>Support SwiftUI: Everything here is built around UIKit. Creating a SwiftUI-compatible version of the OptionsViewController and the bottom sheet would bring this to the future of Apple development.</li><li>Support async/await: The current system uses closures for networking. Moving to Swift’s modern async syntax would improve readability, simplify error handling, and reduce nesting.</li><li>Enhanced Query Support: While we support injecting query dictionaries into the path, a more expressive query system — maybe even a DSL — would make filtering more powerful, readable, and safer.</li></ul><p>These are the next steps I’m genuinely excited to explore. I hope someone reading this might build the SwiftUI version or suggest clever ways to inject async into the current pipeline.</p><h3>🧠 Paragraph 10: What I Learned</h3><p>Writing this system wasn’t just about code — it was about restraint. Knowing <em>when not to overengineer</em>, <em>when to abstract</em>, and <em>how to communicate intent</em> clearly through protocol names and method signatures.</p><p>It taught me:</p><ul><li>That <strong>default behavior is powerful</strong> when designed right.</li><li>That <strong>protocols are like contracts</strong> — clear, flexible, and scalable.</li><li>That good architecture isn’t about cleverness, but <strong>about clarity</strong>.</li><li>That writing reusable, readable systems makes you a better teammate, not just a better coder.</li></ul><p>And most importantly?</p><p>That even a boring form system… can be beautiful.</p><h3>🧶 Conclusion — From Chaos to Craft</h3><p>Behind every line of this architecture lies a deeper story. I wasn’t always in Cairo, surrounded by Swift files and clean abstractions. I’m from Gaza. I left during the war, carrying more pain than luggage. I lost my home, my office, my quiet space to think — and found myself in a noisy, unfamiliar city with no friends, only loneliness and a borrowed laptop.</p><p>But I had code. And code gave me structure when the world didn’t.</p><p>This system, these protocols, this entire article — they weren’t just about UX polish. They were my way of reclaiming control, of building something elegant when everything else felt shattered.</p><p>And now I’m building more — my own framework: Bond, a modular way to structure Flutter apps with the same obsession for clarity you saw here.</p><p>👉 Need a consultation on architecture? 👉 Want to refactor legacy forms? 👉 Need help bringing clarity to your design?</p><p>DM me on LinkedIn or reach out. I’m available for consulting hours, code audits, or just a chat with someone who loves solving UI chaos.</p><p>📩 <a href="https://www.linkedin.com/in/salah-amassi-a73250135/">Connect with me on LinkedIn</a></p><p>Follow my tech journey</p><p>🐦 Twitter/X: <a href="https://x.com/salahamassi">@salahamassi</a></p><p>📸 Instagram: <a href="https://instagram.com/salahamassi">@salahamassi</a></p><p>🐙 GitHub: <a href="https://github.com/salahamassi">salahamassi</a></p><p>Let’s build something elegant together. ❤️</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcb76adead7c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Start-up’s Guide to the iOS User Notifications Framework]]></title>
            <link>https://medium.com/@salahamassi/a-start-ups-guide-to-the-ios-user-notifications-framework-68d52de00ef8?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/68d52de00ef8</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[user-notification]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Thu, 17 Aug 2023 00:43:33 GMT</pubDate>
            <atom:updated>2025-06-08T23:54:35.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cEUk7cHi1hODZQD1u5RvSA.png" /></figure><p>In today’s digital era, the iOS User Notifications Framework isn’t just a developer’s tool — it’s a gateway for startups to engage and retain users. Notifications have evolved from mere alerts to intelligent messages that amplify user experience.</p><h3>So, why should a startup care?</h3><p>For startups, every tool matters, and understanding the User Notifications Framework can be the edge they need. It enhances app functionality, marketing strategies, and overall user engagement.</p><h3>It’s Not Just About Coding; It’s About Crafting Experiences.</h3><p>While the immediate assumption might be that such a technical framework is solely the domain of developers, that’s a misconception. Yes, developers play a pivotal role in integrating and implementing notifications, but the effectiveness of those notifications?</p><p>That’s a collaborative effort.</p><p><strong>Product Managers:</strong> You’re the visionaries, mapping out the product roadmap and user journey. With a deep understanding of the iOS notifications capabilities, you can ensure that user touchpoints are optimized, relevant, and timely.<br><strong>Product Designers: </strong>How a notification looks, feels, and interacts with the user falls into your domain. Is it visually appealing? Is it intuitive? Does it align with the product’s design language? Knowledge of this framework enables you to design enriched user experiences.<br><strong>Marketers: </strong>The timing, messaging, and strategy behind each notification can make or break user engagement. By understanding the different types of notifications and their functionalities, you can tailor your campaigns to be more effective, timely, and user-centric.</p><p>This article dives deep into the framework, offering insights for every role in a startup. Whether you’re developing, designing, strategizing, or managing, you’ll find value here. Let’s unlock the potential of notifications, ensuring your startup stands out in the crowded digital space.</p><h3>Visual Updates: Making Notifications Engaging</h3><p>Imagine a notification as a window — a glimpse into an app’s universe. For those crafting this window, Apple’s User Notifications Framework offers a vast canvas. Let’s dive into how you can paint it vividly.</p><h3><strong>1. Start Simple: The Basics</strong></h3><p>Every story starts with a title. A notification does too. It’s the headline, followed by the body — the core message you want to convey.</p><p><em>For Developers:</em> Here’s a basic example:</p><pre>let center = UNUserNotificationCenter.current()<br><br>let content = UNMutableNotificationContent()<br>content.title = &quot;Daily Reminder!&quot;<br>content.body = &quot;Don&#39;t forget to check our latest offers.&quot;<br>let request = UNNotificationRequest(identifier: UUID().uuidString,<br>                                            content: content,<br>                                            trigger: nil)<br>try await center.add(request)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*67K2hMdsgZZWITGmNoHlEg.png" /></figure><h3><strong>2. Multimedia Engagement</strong></h3><p>Imagine receiving a notification that not only tells you something but also shows it to you, or even plays a sound or video clip. With the iOS User Notifications Framework, notifications can come alive with images, sounds, or even video snippets. These multimedia enhancements can make notifications more dynamic and engaging.</p><p><em>For Developers:</em> Add an attachment like this:</p><pre>let center = UNUserNotificationCenter.current()<br><br>let content = UNMutableNotificationContent()<br>content.title = &quot;Daily Reminder!&quot;<br>content.body = &quot;Don&#39;t forget to check our latest offers.&quot;<br>content.categoryIdentifier = categoryIdentifier<br><br>let url = Bundle.main.url(/service/forresource: &quot;promo&quot;, withExtension: &quot;jpg&quot;)!<br>let attachment = try UNNotificationAttachment(identifier: &quot;promoImage&quot;,<br>                                              url: url,<br>                                              options: .none)<br>// attachment can be image, video or audio<br>content.attachments = [attachment]<br><br><br>let request = UNNotificationRequest(identifier: UUID().uuidString,<br>                                               content: content,<br>                                               trigger: nil)<br>try await center.add(request)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uXkSIE_ust8DXNQhAzX6vg.png" /><figcaption>notification with image attachment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*whvvzb5RRWKDD2rcOiy7nQ.png" /><figcaption>expanded image notification</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-tuxJHBA2Xpaqk18phmlw.png" /><figcaption>notifications with an audio attachment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fSa82HEHRnx23rWhXYlRlQ.png" /><figcaption>notification with a video attachment</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6pCoytDZfz1FdcTdwZY-rA.png" /><figcaption>expanded video notification</figcaption></figure><p>With the ability to incorporate a rich variety of media, your notifications can offer a multi-sensory experience, bridging the gap between mere information and genuine engagement.</p><h3><strong>3. CTA (Call To Action): Notification with Action Buttons</strong></h3><p>Interactivity is the key. Imagine getting a message notification and replying directly from it — without opening the app. Or perhaps a promotional notification that you can act upon right away. Action buttons are your cues to the user, prompting them to, well, take action!</p><h4><strong>What is a CTA in Notifications?</strong></h4><p>A CTA in a notification prompts the user to take immediate action directly from the notification itself. Instead of merely informing users, it encourages them to interact with the content presented, leading them to a more engaged app experience.</p><p>For instance, a messaging app can have a “Reply” button on a message notification, or a news app can offer options like “Read Now” or “Save for Later” right within the notification.</p><h4>How Action Buttons Work in iOS:</h4><p>iOS provides a mechanism to add action buttons to notifications using the UNNotificationAction class. These actions, when tapped, can either lead the user to the app or can be handled in the background.</p><pre>let replyActionIdentifr = &quot;reply&quot;  // we will it later read user input value<br>let markReadActionIdentifr = &quot;mark.read&quot; // will it later pefrom the action<br>let replyAction = UNTextInputNotificationAction(identifier: replyActionIdentifr, title: &quot;Reply&quot;, options: [], textInputButtonTitle: &quot;Send&quot;, textInputPlaceholder: &quot;Type your message...&quot;)<br>let markAsReadAction = UNNotificationAction(identifier: markReadActionIdentifr, title: &quot;Mark as Read&quot;, options: [])<br><br>let category = UNNotificationCategory(identifier: &quot;message&quot;, actions: [replyAction, markAsReadAction], intentIdentifiers: [], options: [])<br>center.setNotificationCategories([category])<br><br>let content = UNMutableNotificationContent()<br>content.title = &quot;New Message&quot;<br>content.body = &quot;You have a new message&quot;<br>content.categoryIdentifier = &quot;message&quot;<br><br>let request = UNNotificationRequest(identifier: UUID().uuidString,<br>                                               content: content,<br>                                               trigger: nil)<br><br>try await center.add(request)</pre><h4>Implications for Different Roles:</h4><p><strong>Marketers:</strong></p><ul><li>Engagement: Having CTAs within notifications can boost app engagement rates. When users can take actions directly from notifications, they’re more likely to interact with the app.</li><li>Campaigns: For promotional campaigns, direct actions like “Shop Now”, “Use Offer”, or “Learn More” can lead to higher conversion rates.</li></ul><p><strong>Product Managers:</strong></p><ul><li>User Flow: CTAs in notifications can streamline user flow. Instead of multiple taps to achieve a task, users can do it directly from the notification.</li><li>Retention: A well-implemented CTA can play a role in user retention, as it keeps users engaged and offers them immediate value.</li></ul><p><strong>Designers:</strong></p><ul><li>UI/UX: Designing clear and concise action buttons is crucial. They need to be intuitive and should fit seamlessly within the aesthetics of the notification.</li><li>User Experience: A well-designed CTA not only looks good but also enhances the user experience, making interactions feel natural and effortless.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RC6YXsh35cgTrPO0zCHSRw.png" /><figcaption>CTA Notification</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cB0EcbdfRB20Sldh9ghtgg.png" /><figcaption>Replay Action</figcaption></figure><h4>Handle the Action &amp; Reading the User Input:</h4><p>Once the user responds to this actionable notification, your app’s notification delegate method userNotificationCenter(_:didReceive:withCompletionHandler:) is triggered:</p><pre>func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -&gt; Void) {<br>    <br>    switch response.actionIdentifier {<br>    <br>    case &quot;reply&quot;: <br>        if let textInputResponse = response as? UNTextInputNotificationResponse {<br>            let userText = textInputResponse.userText<br>            print(&quot;User said: \(userText)&quot;)<br>            // Handle the user&#39;s reply, e.g., by sending it as a message.<br>        }<br>        <br>    case &quot;mark.read&quot;:<br>        // Mark the chat as read in your app&#39;s database or inform the server<br>        print(&quot;Marked as read&quot;)<br>        // Implement the actual marking function here.<br>        <br>    default:<br>        break<br>    }<br>    <br>    completionHandler()<br>}</pre><p>In this function, we handle the case when a user replies using a UNTextInputNotificationAction (which lets a user type a reply directly from the notification) and also handle a regular UNNotificationAction for marking a chat as read.</p><h3><strong>5- Grouping Notifications</strong></h3><p>Think of notification grouping as a virtual assistant tidily organizing your desk. When multiple notifications come from the same app, rather than displaying them as separate items, they are bundled together based on a topic or thread. This means fewer interruptions and a more streamlined experience.</p><p>For instance, imagine you have a shopping app. Instead of showing three different notifications for three separate deals, these notifications can be grouped under the title “Today’s Top Deals.</p><p>Or imagine you’re developing a messaging app, similar to WhatsApp, iMessage, or Telegram. Users in your app can have one-on-one conversations as well as group chats. Every time a user receives a message, a notification is sent to their device. If these notifications aren’t grouped properly, it could lead to a very cluttered and overwhelming notification center.</p><p><em>For Designers and Marketers:</em> Grouping provides an opportunity to create a narrative or theme around your notifications. Instead of sending disparate messages, think about how they can be bundled to tell a more cohesive story or provide comprehensive information on a particular topic.</p><p><em>For Developers:</em> Here’s how you implement grouping:</p><pre>let center = UNUserNotificationCenter.current()<br><br><br>let threadIdentifier = &quot;messages&quot;<br>let content = UNMutableNotificationContent()<br>content.title = &quot;Bond Shop&quot;<br>content.body = &quot;new item&#39;s are available!&quot;<br>content.threadIdentifier = threadIdentifier<br>let request = UNNotificationRequest(identifier: UUID().uuidString,<br>                                               content: content,<br>                                               trigger: nil)<br>try await center.add(request)<br><br>let otherContent = UNMutableNotificationContent()<br>otherContent.title = &quot;Bond Shop&quot;<br>otherContent.body = &quot;don&#39;t forget to check the new items!&quot;<br>otherContent.threadIdentifier = threadIdentifier<br><br>let otherRequest = UNNotificationRequest(identifier: UUID().uuidString,<br>                                               content: otherContent,<br>                                               trigger: nil)<br>try await center.add(otherRequest)</pre><p>In the code above, the threadIdentifier property is used to group notifications. All notifications with the same threadIdentifier will be displayed as a group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AFJ4o4YSlzNr6ITJ2NRAgg.png" /><figcaption><strong>Grouping Notifications</strong></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JyPeOhK1dpKx3-oZWyPThw.png" /><figcaption><strong>Grouping Notifications</strong></figcaption></figure><h3>6- Tailoring the Experience: Customizing Push Notification Content</h3><h4>What is a Push Notification?</h4><p>In the simplest terms, a push notification is a message that pops up on a mobile device. They can appear irrespective of any activity happening on the device, meaning you don&#39;t have to be using the app to receive one. Push notifications are a direct line to users, informing them of new content, reminding them to engage with an app, or offering promotions and updates.</p><h4>Enable Push Notifications (For developers)</h4><ol><li>Open your Xcode project.</li><li>Select your app’sNotification target, then go to the “Signing &amp; Capabilities” tab.</li><li>Click the “+ Capability” button and add “Background Modes.”</li><li>Check “Remote notifications” under Background Modes.</li></ol><h4>Why Customize Push Notifications?</h4><p>Customizing push notifications isn&#39;t just about aesthetics; it&#39;s about delivering the right content to the right user at the right time. Here&#39;s why it&#39;s essential:</p><ol><li>Relevance: One-size-fits-all rarely works. Users have different preferences, and a personalized notification can resonate more effectively than a generic one.</li><li>Engagement: Customized notifications, tailored to user behavior or preferences, are more likely to be opened.</li><li>Retention: With the sheer volume of apps and notifications users receive, standing out with a unique and personalized notification can be a key factor in retaining users.</li></ol><h3>How to Customize Push Notifications: (For developers)</h3><p>iOS offers mechanisms to not only send simple text-based notifications but also to include media attachments and even customize the layout and behavior of notifications.</p><h4>Creating and Understanding the UNNotificationServiceExtension</h4><h3>Creating and Understanding the UNNotificationServiceExtension</h3><p>When it comes to tailoring the notification content as it arrives, UNNotificationServiceExtension is your go-to tool. This extension lets developers modify the content of remote notifications before they are delivered to the user. Let&#39;s dive into creating this extension step by step:</p><h4>1. Creating a New Target:</h4><p>The UNNotificationServiceExtension exists as a separate entity from your main application. Therefore, the first step involves adding a new target to your Xcode project.</p><p><strong>Steps:</strong></p><ol><li>Open your Xcode project.</li><li>Select File &gt; New &gt; Target.</li><li>From the template chooser, pick the Notification Service Extension option.</li><li>Click Next and provide a name for your extension.</li><li>Click Finish.</li></ol><p>You will now have a new folder in your Xcode project dedicated to the Notification Service Extension, complete with its own Info.plist file and a .swift source file.</p><h4>2. Why a Separate Target?</h4><p>Having the service extension in a separate target ensures that the code responsible for modifying the content of the notification is isolated from the rest of your app. This separation is also a security feature. It limits the processing of notification content to a restricted environment, reducing the potential harm from malicious notifications.</p><h4>3. Implementing the Extension:</h4><p>The main logic goes into the .swift source file generated for the extension. The key method to override is didReceive(_:withContentHandler:).</p><p><strong>Example Implementation:</strong></p><pre>import UserNotifications<br><br>class NotificationService: UNNotificationServiceExtension {<br><br>    var contentHandler: ((UNNotificationContent) -&gt; Void)?<br>    var bestAttemptContent: UNMutableNotificationContent?<br><br>    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -&gt; Void) {<br>        self.contentHandler = contentHandler<br>        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)<br>        <br>        guard let bestAttemptContent = bestAttemptContent else { return }<br>        <br>        // Assuming the URL for the image is present in the push payload under the key &quot;image-url&quot;<br>        if let imageUrlString = request.content.userInfo[&quot;image-url&quot;] as? String, let imageUrl = URL(string: imageUrlString) {<br>            downloadImage(from: imageUrl) { (attachment) in<br>                if let attachment = attachment {<br>                    bestAttemptContent.attachments = [attachment]<br>                }<br>                contentHandler(bestAttemptContent)<br>            }<br>        } else {<br>            contentHandler(bestAttemptContent)<br>        }<br>    }<br>    <br>    private func downloadImage(from url: URL, completion: @escaping (UNNotificationAttachment?) -&gt; Void) {<br>        let task = URLSession.shared.dataTask(with: url) { (data, _, error) in<br>            guard let data = data, error == nil else {<br>                completion(nil)<br>                return<br>            }<br>            <br>            let temporaryDirectory = NSTemporaryDirectory()<br>            let temporaryFile = URL(fileURLWithPath: temporaryDirectory).appendingPathComponent(UUID().uuidString + &quot;.png&quot;)<br>            <br>            do {<br>                try data.write(to: temporaryFile)<br>                let attachment = try UNNotificationAttachment(identifier: &quot;image&quot;, url: temporaryFile, options: nil)<br>                completion(attachment)<br>            } catch {<br>                print(&quot;Error saving the image: \(error)&quot;)<br>                completion(nil)<br>            }<br>        }<br>        task.resume()<br>    }<br>}<br></pre><h4>4. Capabilities and Entitlements:</h4><p>If your notification modifications require network access (e.g., to download an image), ensure that you enable the ‘App Groups’ capability for both your main app and the extension, and they both share the same app group. This is necessary because extensions and main applications do not share data directly, but app groups provide a bridge to share certain types of data.</p><h4>5. Understanding Time Limits:</h4><p>It’s essential to know that the UNNotificationServiceExtension is time-sensitive. From the moment a push notification arrives until the contentHandler callback is executed, you have only a short amount of time (seconds) to perform your modifications. Therefore, operations like networking should be as efficient as possible. If the allocated time expires, the system will show the original content of the notification.</p><h3>Personalized Layouts with Notification Content Extension</h3><p>The Notification Content Extension provides developers with a way to offer a custom user interface for the notifications delivered to their app. With it, not only can you change the appearance of the notification, but you can also allow user interaction beyond just the action buttons.</p><p>Creating a Notification Content Extension: Step-by-Step</p><h4><strong>1- Adding a New Target to Your Project:</strong></h4><ul><li>Open your Xcode project.</li><li>Go to File &gt; New &gt; Target.</li><li>Choose the ‘Notification Content Extension’ template.</li><li>Click Next, provide a name for your extension, and complete the setup</li></ul><h4><strong>2- Configuring the Info.plist:</strong></h4><ul><li>After creating the extension, you&#39;ll find a new Info.plist file in the extension folder.</li><li>You&#39;ll need to specify which types of notifications should use your custom content. This is done by setting the UNNotificationExtensionCategory key to the identifier of your notification category.</li></ul><h4>3- Designing the Interface:</h4><ul><li>Navigate to the Interface Builder file (usually named MainInterface.storyboard) in the extension target.</li><li>Customize the view to your liking, much like you would any other storyboard.</li></ul><h4>4- Implementing the Code:</h4><ul><li>The Notification Content Extension comes with a default view controller. You’ll write the logic to update the UI based on the notification content here.</li></ul><p><strong>Interface:</strong></p><p>In your MainInterface.storyboard, you can design a view with:</p><ul><li>A label asking “How would you rate our app?”</li><li>Five buttons, each representing a star.</li></ul><p><strong>Code:</strong></p><p>In your extension’s default view controller (NotificationViewController.swift or similar), you&#39;d do something like this:</p><pre>import UIKit<br>import UserNotifications<br>import UserNotificationsUI<br><br>class NotificationViewController: UIViewController, UNNotificationContentExtension {<br><br>    @IBOutlet weak var feedbackLabel: UILabel!<br><br>    func didReceive(_ notification: UNNotification) {<br>        self.feedbackLabel.text = notification.request.content.body<br>    }<br><br>    @IBAction func rateApp(_ sender: UIButton) {<br>        // Logic to handle rating - You&#39;d probably want to send this back to your server<br>        switch sender.tag {<br>        case 1: <br>            feedbackLabel.text = &quot;Thanks for the 1-star rating!&quot;<br>        case 2: <br>            feedbackLabel.text = &quot;Thanks for the 2-star rating!&quot;<br>        // ... And so on for the other stars<br>        default:<br>            break<br>        }<br>    }<br>}</pre><p>The example above assumes you’ve connected the buttons to the rateApp action and set their tags from 1 to 5 for each star.</p><blockquote>Make sure to send a test push notification with the category you specified in the Info.plist (UNNotificationExtensionCategory key).</blockquote><blockquote>Remember, the Notification Content Extension runs separately from your main app, which means it doesn’t have direct access to the app’s data or functions. If needed, you can utilize app groups to share data.</blockquote><p>— -</p><h3>Notification Permissions</h3><h4>For PMs, Product Designers, and Marketers:</h4><p>When asking users for notification permissions, it’s not a one-size-fits-all. Depending on your app’s functionality and what you wish to notify users about, you can ask for specific permissions:</p><p>1. <strong>Badge</strong>: Allows your app to display a number on the app icon, indicating the number of notifications.<br> <br>2. <strong>Sound</strong>: Your app can play a sound when a notification is delivered.</p><p>3. <strong>Alert</strong>: Presents a message on the device’s screen.</p><p>4. <strong>CarPlay</strong>: If users have CarPlay, notifications can appear there.</p><p>5. <strong>Critical Alert</strong> (iOS 12.0 and above):* Reserved for critical notifications that require immediate attention. E.g., health-related alerts.</p><p>6. <strong>Provides App Notification Settings</strong> (iOS 12.0 and above): This allows users to dive into the app’s specific notification settings directly from the system settings like the WhatsApp app.</p><p>7. <strong>Provisional</strong> (iOS 12.0 and above): Allows sending notifications without asking for permission first. However, these notifications are silent and show up only in the notification center.</p><p><strong>Real-World Scenarios</strong>: An e-commerce app might primarily focus on badge, sound, and alert permissions to inform users about deals. In contrast, a medical app might require critical alert permissions to remind users of medicine timings or critical health alerts.</p><h4>For Developers:</h4><p>When requesting permissions, you can ask for multiple at once. Here’s how:</p><pre>do {<br>  let options: UNAuthorizationOptions = [.badge, .sound, .alert, .carPlay, .criticalAlert, .providesAppNotificationSettings, .provisional]<br>  let center = UNUserNotificationCenter.current()<br>  let granted = try await center.requestAuthorization(options: options)<br>  if granted {<br>   /// we got the Permissions <br>  }<br>} catch {<br>  // handel errors<br>}</pre><p>Remember to always keep the user experience in mind. Overwhelming users with too many notifications or not respecting their preferences can lead to them disabling notifications for your app entirely or worse, uninstalling it.</p><h3>Notification Interruption Levels</h3><h4>Understanding Notification Interruption Levels</h4><p>Notifications are a powerful tool for user engagement, but it’s essential to use them judiciously to avoid user annoyance or burnout. This is where iOS’s Notification Interruption Levels come into play:</p><p>1. <strong>Passive</strong>: These notifications are added to the notification list but won’t light up the screen or play any sound. Ideal for non-urgent information that can wait until the user checks their notifications.<br> <br> <strong>Example</strong>: A daily recap, friend suggestions, or content recommendations.</p><p>2. <strong>Active</strong>: These notifications are presented immediately, lighting up the screen and possibly playing a sound. Best for messages that require more immediate attention but aren’t urgent.</p><p><strong>Example</strong>: A new direct message, a comment on a post, or a live event starting soon.</p><p>3. <strong>Time-Sensitive</strong>: Notifications that light up the screen, play a sound, and can even be presented during Do Not Disturb mode and other custom fouce modes. Reserved for urgent messages that the user should be aware of immediately.<br> <br> <strong>Example</strong>: A ride-share arriving, a two-factor authentication code, or a last-minute event change.</p><p>4. <strong>Critical</strong>: These are high-priority notifications that light up the screen, always play a sound (even if the device is muted), and always show up during Do Not Disturb mode and other custom fouce modes. Use these sparingly and only for truly critical alerts.<br> <br> <strong>Example</strong>: Medical or safety alerts, security breaches, or extreme weather warnings.</p><p>By choosing the right level, you can ensure that your app communicates effectively without overwhelming or annoying the user.</p><h4>For Developers:</h4><p><strong>Setting the `interruptionLevel` for Notifications in Swift:</strong></p><p>Here’s how you can set different interruption levels for local notifications:</p><pre>let content = UNMutableNotificationContent()<br>content.title = &quot;Example Title&quot;<br>// Set interruption level based on the context:<br>// Passive<br>content.interruptionLevel = .passive<br>// Active<br>// content.interruptionLevel = .active<br>// Time-Sensitive (Remember you need special entitlement for this)<br>// content.interruptionLevel = .timeSensitive<br>// Critical <br>// content.interruptionLevel = .critical<br>// Rest of your notification code…</pre><h4>Setting interruptionLevel in Push Notification Payload</h4><pre>{<br>    &quot;aps&quot;: {<br>        &quot;alert&quot;: {<br>            &quot;title&quot;: &quot;Example Title&quot;,<br>        },<br>        &quot;interruption-level&quot;: &quot;passive&quot; // time-sensitive, active, critical<br>    },<br>}</pre><p>By understanding and properly implementing these levels, developers can ensure that notifications are delivered in a way that aligns with their importance and the user’s needs.</p><h4>Enabling Time-Sensitive Notifications:</h4><p>To utilize Time-Sensitive notifications, developers need to enable the custom code capability in their Xcode project:</p><ol><li>Open your project in Xcode.</li><li>Click on your main app target, navigate to the “Signing &amp; Capabilities” tab.</li><li>Click on the “+” button to add a capability.</li><li>Search for and add “Time-Sensitive Notifications”.</li></ol><blockquote>Remember, while Time-Sensitive notifications have the ability to interrupt users more assertively, they should be used judiciously to avoid overwhelming or annoying users.</blockquote><h3>Notification Delivery Options</h3><p>There are two primary ways your notifications get delivered:</p><p><strong>Immediate Delivery</strong>: The user is alerted as soon as the notification arrives.</p><p><strong>Scheduled Summary</strong>: Notifications are bundled and delivered at specific times, reducing constant pings and distractions.</p><p><strong>Real-World Scenario:</strong> Imagine a news app. Breaking news alerts should be immediate, while daily summaries can be bundled into the Scheduled Summary.</p><p>Immediate notifications are the default. For scheduled summaries, you rely on user preferences and notification importance levels.</p><p>Set non-urgent notifications at a lower importance level so iOS knows they can be summarized.</p><p>adjusting the interruptionLevel for your notifications. iOS provides multiple levels of interruption, including &quot;active&quot; (immediate interruption), &quot;time-sensitive&quot; (break through Do Not Disturb and Focus modes for urgent messages), &quot;passive&quot; (won&#39;t wake the screen or play a sound), and &quot;none&quot;.</p><p>For non-urgent notifications, you may want to use the “passive” level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*JrYQIURyvijrgw9P.png" /></figure><h3>Communication Notifications</h3><p>Communication notifications are specifically designed for direct personal communications.</p><p>They:</p><ul><li>Have a distinct user interface featuring prominent avatars and group names.</li><li>Can break through scheduled notification summaries by default.</li><li>Can potentially bypass a user’s Focus settings.</li></ul><p>This feature enables apps to provide a richer, more prominent notification experience for direct personal communications. It also ensures that important personal messages and calls are less likely to be missed even when the user has set Focus modes or scheduled summaries. This could potentially increase user engagement and retention for communication-centric apps. However, misuse might lead to a poor user experience, so it’s crucial to ensure that only genuine personal communications use this feature.</p><h4>Setting up Communication Notifications</h4><p>1. <strong>Enable the Capability</strong>:<br> <br> — In Xcode, for your app target, enable the “Communication Notifications” capability.<br> — For each intent your app supports, add its class name to the `NSUserActivityTypes` array in your `Info.plist`.</p><p>2. <strong>Identify the Participants</strong>:<br> <br> — For each communication, create an `INPerson` object for every participant involved.<br> — The current user, by default, is the recipient and shouldn’t be explicitly included.</p><p>3. <strong>Configure Intents for Communication Types</strong>:<br> <br> — For messages: Use `INSendMessageIntent`. This is intended for text messages.<br> — For calls: Use `INStartCallIntent`. This is intended for call notifications.<br> <br>4. <strong>Donating Interactions and Updating Notifications</strong>:</p><p>- After setting up an intent, create an interaction for the intent using `INInteraction`.<br> — Indicate the interaction direction (incoming/outgoing).<br> — Donate the interaction and, if successful, update the content of the received notification to display it as a communication notification.</p><p>5. <strong>Handle Outgoing Interactions</strong>:</p><p>- For outgoing communications, Siri uses these to refine its suggestions. <br> — It’s similar to incoming interactions, but the direction is set to `outgoing`.</p><h4><strong>Example for Handling an Incoming Message</strong></h4><pre>import Intents<br><br>func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -&gt; Void) {<br><br>  let sender = INPerson(personHandle: INPersonHandle(value: &quot;+123456732&quot;, type: .phoneNumber),<br>                         nameComponents: nil,<br>                         displayName: &quot;Salah Nahed&quot;, <br>                         image: nil,<br>                         contactIdentifier: nil,<br>                         customIdentifier: nil)<br><br>  let recipient = INPerson(personHandle: INPersonHandle(value: &quot;+1234567890&quot;, type: .phoneNumber),<br>                         nameComponents: nil,<br>                         displayName: &quot;John Doe&quot;, <br>                         image: nil,<br>                         contactIdentifier: nil,<br>                         customIdentifier: nil)<br><br>  // Create the intent<br>  let intent = INSendMessageIntent(recipients: [recipient],<br>                                 content: &quot;Hello, John!&quot;,<br>                                  outgoingMessageType: .outgoingMessageText,<br>                                 speakableGroupName: nil,<br>                                 conversationIdentifier: nil,<br>                                 serviceName: nil,<br>                                 sender: sender)<br><br>    // Initializing the interaction<br>    let interaction = INInteraction(intent: intent, response: nil)<br><br>    // Setting the interaction direction as incoming<br>    interaction.direction = .incoming<br><br>    // Donating the interaction<br>    interaction.donate { error in<br>        if let error = error {<br>            return<br>        }<br>       <br>        let content = request.content<br>        <br>        do {<br>            let updatedContent = try content.updating(from: intent)<br>            contentHandler(updatedContent)<br>        } catch {<br>            // Handle errors<br>        }<br>    }<br>}<br><br><br></pre><h3>Donating Interactions for Communication Notifications</h3><p>Certainly! Interaction donations using SiriKit play a pivotal role in enhancing the intelligence of the system-wide user experience on iOS devices. By donating interactions, you give the system information about tasks and actions users frequently perform in your app. The system can then use this information to make your app more discoverable and easily accessible to the user in various contexts.</p><p>When you donate a communication-related interaction, you’re telling the system about a communication event, such as a sent message or an incoming call. This donation can directly influence Siri suggestions and other system features in the following ways:</p><ol><li><strong>Siri Suggestions</strong>:<br> <br> — Siri might suggest your app or specific actions from your app based on previous interactions. For instance, if a user frequently chats with a particular contact through your app in the evenings, Siri might suggest starting a chat with that contact around that time.<br> — The suggestion can appear in various places, including the lock screen, in search, or even when using Siri.</li></ol><p>2. <strong>Share Sheet Recommendations</strong>:</p><p>- When users want to share content, they often see a list of suggested contacts and apps in the Share Sheet. If you’ve donated a message interaction, the person the user frequently communicates with through your app might appear as a suggestion in the Share Sheet, making it easier for the user to share content directly with that contact.<br> <br>3. <strong>Contact Suggestions</strong>:<br> <br> — If you provide information linking a participant in a communication to a contact in the user’s address book (by providing the contact identifier or by matching an email or phone number), then when the user searches or engages with that contact, your app might be suggested as a way to communicate with that contact.<br> — This linking can also help ensure that communication notifications are more accurate and enriched, showing user-recognized avatars or names from their contacts.</p><h4>Importance of Correct and Ethical Donations</h4><p>For the best user experience, it’s vital to ensure that:</p><p>- <strong>Relevance</strong>: Only genuine and user-relevant interactions are donated. Overloading with non-relevant donations can reduce the effectiveness of Siri’s suggestions.<br> <br>- <strong>Privacy</strong>: Ensure that any donated interaction respects the user’s privacy and doesn’t inadvertently share sensitive information. Apple places a strong emphasis on user privacy, and so should your app.<br> <br>- <strong>Up-to-date</strong>: Regularly remove outdated donations. For example, if a user deletes a message thread or stops communicating with a contact, you might want to delete any interactions related to that thread or contact.</p><p>In conclusion, by effectively utilizing interaction donations for communication events, you can make your app more integrated with the iOS ecosystem, providing users with intelligent suggestions and shortcuts that can make their experience more fluid and efficient.</p><h3>Conclusion</h3><p>The iOS User Notifications Framework serves as a powerful instrument for startups to enhance user engagement and retention. Its capabilities extend beyond mere alerts, allowing for enriched experiences. With multimedia attachments, call-to-action buttons, and a variety of customization options, notifications can truly stand out. Furthermore, grouping notifications and scheduling them at appropriate times ensures that users receive relevant information without feeling overwhelmed. The synergy between different roles in a startup, such as developers, designers, product managers, and marketers, is vital to harness the full potential of this framework.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68d52de00ef8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Service Providers in Flutter Bond: A Hands-on Approach]]></title>
            <link>https://medium.com/@salahamassi/understanding-service-providers-in-flutter-bond-a-hands-on-approach-c124f9d50cfe?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c124f9d50cfe</guid>
            <category><![CDATA[service-locator]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Wed, 17 May 2023 12:50:08 GMT</pubDate>
            <atom:updated>2023-05-18T20:47:40.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/486/0*TlmEkC1hPsqj0CCZ.png" /></figure><p>As Flutter developers, we are always seeking to simplify and streamline our code. Flutter Bond offers an innovative and efficient approach to managing dependencies through its Service Provider concept. This article will dive into how Service Providers work in Flutter Bond and how they contribute to writing cleaner, scalable, and well-architected code.</p><h4>What is a Service Provider?</h4><p>A Service Provider in Flutter Bond is a class that registers dependencies in a project. By managing instances of services, it enables easy access and efficient utilization throughout the application. In Flutter Bond, developers create a separate Service Provider for each feature, such as authentication (Auth feature), post management (Post feature), and so on.</p><p>Here’s a basic structure of a service provider class:</p><pre>class PackagesServiceProvider extends ServiceProvider {<br><br>  @override<br>  Future&lt;void&gt; register(GetIt it) async {<br>    it.registerLazySingleton(() =&gt; PackagesApiService(it()));<br>    it.registerFactory(() =&gt; PackagesCubit(it()));<br>  }<br>}</pre><h3>Service Providers and GetIt</h3><p>Service Providers in Flutter Bond use <a href="https://pub.dev/packages/get_it">GetIt</a>, a simple service locator for Dart and Flutter projects. GetIt ensures easy access to services and models from anywhere in the application, facilitating efficient dependency management.</p><h4>Defining Model serialization factory in a Service Provider</h4><p>Within a Service Provider, developers define how to convert each model from JSON to an object using the responseConvert method.</p><pre>class PackagesServiceProvider extends ServiceProvider {<br>  @override<br>  Future&lt;void&gt; register(GetIt it) async {<br>    //register dependencies<br>  }<br><br>  @override<br>  T? responseConvert&lt;T&gt;(Map&lt;String, dynamic&gt; json) {<br>    if (T == Package) {<br>      return Package.fromJson(json) as T;<br>    } else if (T == Cart) {<br>      return Cart.fromJson(json) as T;<br>    } else if (T == Order) {<br>      return Order.fromJson(json) as T;<br>    }<br>    return null;<br>  }<br>}</pre><p>This method is used inside the ResponseConverter class and returns a model instance from a JSON response.</p><p>The ResponseConverter class iterates through all registered service providers and uses the responseConvert method to convert the JSON object into the appropriate model. Here is an example of what happened inside the response converter:</p><pre>class ResponseConverter&lt;T&gt; implements JsonConverter&lt;T, Object&gt; {<br>  const ResponseConverter();<br><br>  @override<br>  T fromJson(Object json) {<br>    if (json is Map&lt;String, dynamic&gt;) {<br>      for (var provider in providers) {<br>        final model = provider.responseConvert&lt;T&gt;(json);<br>        if (model != null) return model;<br>      }<br>    }<br>    return json as T;<br>  }<br>}</pre><p>This approach eliminates the need for extensive if-else statements for each model. For example, instead of having this:</p><pre>class ResponseConverter&lt;T&gt; implements JsonConverter&lt;T, Object&gt; {<br>  const ResponseConverter();<br><br>  @override<br>  T fromJson(Object json) {<br>    if (json is Map&lt;String, dynamic&gt;) {<br>      if (T == Conversation) {<br>        return Conversation.fromJson(json) as T;<br>      }<br>      // More else-if statements for each model... <br>    }<br>    return json as T;<br>  }<br>}</pre><p>The ResponseConverter class in the above examples is a key part of the JSON serialization process in Flutter. It extends the JsonConverter class from the json_annotation package. This package, along with it, forms the backbone of JSON serialization in Flutter.</p><p>If you’re unfamiliar with these concepts or want a refresher, check out the following resources:</p><ul><li><a href="https://pub.dev/packages/json_serializable">JsonSerializable Package Documentation</a>: This provides an overview of the json_serializable package, including how to use it in your projects.</li><li><a href="https://flutter.dev/docs/development/data-and-backend/json">Official Flutter Documentation on JSON and Serialization</a>: This is an extensive guide on handling JSON in Flutter, including using the json_serializable package.</li></ul><h4>Creating a Service Provider for Third-Party Integrations</h4><p>In many applications, you might need to integrate third-party services such as Firebase, Facebook Pixel, or AppFlyer. These services provide essential functionalities ranging from analytics tracking, user authentication, database management, and more. With the Service Provider system in Flutter Bond, this process becomes straightforward.</p><p>Let’s take Firebase as an example. Here’s how you can create a Service Provider for Firebase:</p><pre>import &#39;package:flutter_bond/core/services/service_provider.dart&#39;;<br>import &#39;package:firebase_core/firebase_core.dart&#39;;<br>import &#39;package:firebase_remote_config/firebase_remote_config.dart&#39;;<br><br>class FirebaseServiceProvider extends ServiceProvider {<br>  @override<br>  Future&lt;void&gt; register(GetIt it) async {<br>    final firebaseApp = await Firebase.initializeApp(<br>      options: DefaultFirebaseOptions.currentPlatform,<br>    );<br>    it.registerSingleton(firebaseApp);<br>    final remoteConfig = FirebaseRemoteConfig.instance;<br>    remoteConfig.setDefaults(UpdateAppDefaultValue.defaultParameters);<br>    await remoteConfig.fetchAndActivate();<br>    it.registerLazySingleton(() =&gt; remoteConfig);<br>  }<br>}</pre><p>In this code snippet, we create a `FirebaseServiceProvider` class that extends `ServiceProvider`. Inside this class, we override the `register` method to initialize Firebase and RemoteConfig. The `register` method will be called when the application starts, initializing all necessary services for the app.</p><p>We then register Firebase and RemoteConfig as services with the GetIt service locator. This makes them globally accessible within our app. The `registerSingleton` and `registerLazySingleton` methods ensure that only one instance of each service is created.</p><p>One important thing to note is the `fetchAndActivate` method for `remoteConfig`. This method fetches and activates the Remote Config parameters, ensuring they are updated and available for use in our app.</p><h4>How to use Service Providers?</h4><p>After creating a Service Provider for a feature or any integrations, developers need to register it in the app.dart file, inside the providers array. This allows the Service Provider to be accessible and useable across the application.</p><pre>final List&lt;ServiceProvider&gt; providers = [<br>  // Framework Service Providers<br>  FirebaseServiceProvider(),<br>  AppServiceProvider(),<br>  AuthServiceProvider(),<br>  ApiServiceProvider(),<br>  CacheServiceProvider(),<br>  AnalyticsServiceProvider(),<br>  NotificationsServiceProvider(),<br>// Modules Service Providers<br>  PackagesServiceProvider(),<br>];</pre><p>By following these steps, you can create Service Providers for any third-party services that your application requires. This not only provides a neat and organized codebase but also ensures easy access to these services throughout your application. Remember, the key is to create a Service Provider, initialize the third-party service within it, and finally, register it in your application. Happy coding!</p><h4>Enhancing the Process with Code Generation</h4><p>Looking ahead, we plan to further streamline the process of creating and registering Service Providers in Flutter Bond. The goal is to leverage the power of code-generation tools, specifically build_runner and code_gen packages, to automate the creation of Service Providers based on configuration files.</p><p>This feature, once implemented, would work as follows: Developers would define the configurations for a specific service in a file, say cache_config.dart. The build_runner would then take this configuration file and generate a corresponding Service Provider class automatically.</p><pre>import &#39;package:bond/core/cache/secure_storage_cache_driver.dart&#39;;<br>import &#39;package:one_studio_core/core.dart&#39;;<br><br>class CacheConfig {<br>  static var defaultStore = &#39;shared_preference&#39;;<br><br>  static var stores = {<br>    &#39;shared_preference&#39;: {<br>      &#39;driver&#39;: &#39;shared_preference&#39;,<br>      &#39;class&#39;: SharedPreferencesCacheDriver,<br>    },<br>    &#39;in_memory&#39;: {<br>      &#39;driver&#39;: &#39;in_memory&#39;,<br>      &#39;class&#39;: InMemoryCacheDriver,<br>    },<br>    &#39;secure_cache&#39;: {<br>      &#39;driver&#39;: &#39;secure_cache&#39;,<br>      &#39;class&#39;: SecureStorageCacheDriver,<br>    },<br>  };<br>}</pre><p>The generated Service Provider would encapsulate all the logic related to the specific service, providing a clear separation of concerns and reducing the chances of errors. It would significantly reduce the manual work involved in writing boilerplate code, allowing developers to focus more on business logic.</p><p>This automation will particularly shine in the configuration of services like cache, notifications, analytics, and more. Each of these services would have its dedicated configuration file, and the build_runner would generate the corresponding Service Provider.</p><p>Please note that this feature is part of our future plans for Flutter Bond. We’re excited about the potential it holds to further enhance the efficiency of the development process and we look forward to implementing it soon.</p><h3>Conclusion</h3><p>Flutter Bond’s Service Provider concept offers an efficient, structured approach to managing dependencies in your Flutter applications. By harnessing the power of service locators and code generation, Flutter Bond allows developers to focus more on crafting exceptional applications and less on manual configuration.</p><p>Stay tuned for more insights into the world of Flutter Bond and how it’s revolutionizing Flutter development practices.</p><p>🔔 Remember, the journey of innovation never stops! 🚀 Stay tuned for more updates and improvements in Flutter Bond. 😊</p><p>Happy coding! 💻🌟</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c124f9d50cfe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Bond: An Innovative Framework for Accelerating Mobile Development]]></title>
            <link>https://medium.com/@salahamassi/flutter-bond-a-laravel-inspired-framework-for-streamlined-mobile-development-8fb28b128ef7?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fb28b128ef7</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[laravel]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Sun, 23 Apr 2023 22:23:30 GMT</pubDate>
            <atom:updated>2023-05-17T06:09:08.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*BfKOVF5Ms5fHMnHTtUZt1A.png" /></figure><h3>Introduction</h3><p>Flutter Bond is a robust and adaptable framework that accelerates the mobile development process for developers of all backgrounds. Drawing inspiration from Laravel and clean architecture principles, particularly the structure and organization of Laravel, Flutter Bond introduces powerful tools and packages for handling API requests, state management, caching, notifications, analytics, and much more. This article will discuss why the Flutter Bond framework was created, the solutions it provides, its components and packages, and what’s next for the project.</p><h3>Why We Need a Flutter Bond Framework</h3><p>As the mobile app development landscape evolves, developers increasingly need to adapt to new technologies and approaches. One of the challenges faced by developers transitioning to mobile development is the lack of familiarity with the tools, libraries, and concepts used in mobile app development. The Flutter Bond framework was born out of a desire to bridge this gap and provide a more familiar environment for developers entering the world of mobile development, especially for those with a background in Laravel and clean architecture principles.</p><p>The framework aims to make it easy for new developers to join and onboard projects quickly, as well as enable developers of various backgrounds to discover and understand mobile projects better. By offering a streamlined development experience, Flutter Bond hopes to empower developers to become mobile full-stack developers capable of working on both backend and mobile projects</p><h3>Flutter Bond Solutions</h3><p>Flutter Bond offers several unique solutions that contribute to its streamlined and efficient approach:</p><ul><li>Bondfire: A powerful API fetching and caching solution that simplifies API request handling and offers various cache policies and custom caching options.</li><li>Cache Solution: A versatile and adaptive caching module designed to streamline data storage and retrieval independently of API calls. It provides an easy-to-use interface with various methods for managing cache data, such as custom expiration times, incrementing or decrementing values, and storing data forever.</li><li>Beacon: A notification handling system that manages in-app notifications and alerts.</li><li>Analytics management: Support for multiple analytics providers, such as Firebase Analytics and Facebook Pixel, enabling developers to gain valuable insights into user behavior and app performance.</li><li>App Router package: A suitable infrastructure for handling iOS Universal Links and Android App Links, making it easier to manage deep linking and app navigation.</li></ul><h3>Bond Components and Packages</h3><p>Some of the key components and packages offered by the Flutter Bond framework include:</p><ul><li>State Management: Flutter Bond utilizes Riverpod as its state management library and Bloc for its business logic components. The framework plans to migrate all Cubits and Blocs to Riverpod providers in the future.</li><li>Dependency Injection: The get_it package is used for registering dependencies within service providers, making it easy to create providers for each integration and feature. All providers are registered before the runApp Flutter method, allowing for efficient unit testing.</li><li>Localization: The intl package is used for localization, and Flutter Bond supports changing the app language on the fly using a global AppBloc.</li><li>Theming: Flutter Bond uses ThemeData to customize themes for all components from a single place. The framework provides appLightThemeData and appDarkThemeData for easy customization and supports changing the app theme on the fly using the global AppBloc.</li><li>Configuration: The framework includes a config directory with files for various configuration purposes, such as analytics.dart, api.dart, cache.dart, and notification.dart. Each file serves as an entry point for providing configurations for analytics, API, cache, or notifications.</li></ul><h3>From Day One: A Comprehensive Framework</h3><p>Flutter Bond has been designed from the ground up to support various essential features, including local and remote notifications, login and registration, social media login (Google and Apple), analytics tools, API fetching with caching abilities, and more. This allows developers to focus on business logic and requirements while the framework takes care of other details.</p><h3>What’s Next</h3><ol><li>Better integration with other state management libraries: While currently using Riverpod as a state management library and Bloc, the plan is to migrate all Cubits and Blocs to Riverpod providers. This migration will allow for a more consistent and efficient state management experience.</li><li>Expanded support for more third-party packages and services: The framework aims to provide seamless integration with various third-party services and packages, such as popular authentication providers, databases, and other essential tools for modern app development.</li><li>Improved documentation and resources: As the framework gains popularity, it’s crucial to provide comprehensive documentation, tutorials, and other resources to help new developers quickly get up to speed with Flutter Bond.</li><li>Active community engagement and support: Encouraging developers to contribute to the framework, submit bug reports, and suggest new features will help drive the continued evolution of Flutter Bond. Establishing a vibrant and supportive community around the framework is essential for its long-term success.</li></ol><p>As the Flutter Bond framework continues to evolve, developers can look forward to new features, improvements, and enhancements designed to further streamline the development process and make it even more efficient and enjoyable. By staying true to its goal of making Laravel backend developers feel more at home in mobile development, Flutter Bond will continue to innovate and expand its offerings to meet the needs of developers in this ever-changing landscape.</p><h3>Conclusion</h3><p>The Flutter Bond framework offers a Laravel-inspired approach to mobile development, providing a familiar environment for Laravel developers and empowering them to become mobile full-stack developers. By offering unique solutions like Bondfire, Beacon, and the App Router package, as well as a streamlined development experience, Flutter Bond is paving the way for more efficient and enjoyable mobile app development.</p><p>With its comprehensive feature set from day one, including support for various essential features like local and remote notifications, login and registration, social media login, analytics tools, and API fetching with caching abilities, developers can focus on business logic and requirements while the framework takes care of other details.</p><p>As the framework continues to evolve, developers can expect even more innovative features and improvements, ensuring that Flutter Bond remains a powerful tool for mobile developers now and into the future.</p><h3>GitHub Repo</h3><p><a href="https://github.com/onestudio-co/flutter-bond">GitHub - onestudio-co/flutter-bond: Your next Flutter project template!</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fb28b128ef7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Flutter Dio Interceptors + Unit Test]]></title>
            <link>https://medium.com/@salahamassi/flutter-dio-interceptors-unit-test-c2795867bbff?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2795867bbff</guid>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[unittest]]></category>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[http-interceptors]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Sun, 18 Dec 2022 22:59:30 GMT</pubDate>
            <atom:updated>2025-06-09T00:00:42.738Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gk8BgYJS_KDKkibVjRoHkQ.png" /></figure><p>Not long ago, we at Famcare worked on the anonymous user feature</p><blockquote>An anonymous login is <strong>a process that allows a user to login to a website anonymously, often by using “anonymous” as the username</strong>. In this case, the login password can be any text, but it is typically a user’s email address. Users are able to access general services or public information by using anonymous logins.</blockquote><blockquote><a href="https://www.techopedia.com/definition/5970/anonymous-login">https://www.techopedia.com/definition/5970/anonymous-login</a></blockquote><p>One of the requirements for this feature was when the user wants to use one of the features that are not authorized to use without logging in, the user is redirected to register and then returns the user to the same place and allows him to use this feature.</p><p>Most of the features in the application are used through API calls.</p><p>Therefore, it was agreed that for the features that the anonymous user is not authorized to use, a custom response is returned from the server, so that the application redirects it to the registration or login screen</p><pre>{<br>   &quot;code&quot;:&quot;anonymous_are_not_allowed&quot;,<br>   &quot;message&quot;:&quot;You are not allowed to use this feature please loging or create an new account&quot;<br>}</pre><h3>Retry on unauthorized Dio Interceptor</h3><p>We Intercept all requests and we just care about requests that returned <strong>anonymous_are_not_allowed</strong> error code.</p><p>when Interceptor catches any request with <strong>anonymous_are_not_allowed code we do two things</strong></p><p>1- Redirect the user to the register page.</p><p>2- use <strong>DioUnauthorizedRequestRetrier </strong>to schedule Request Retry after the user successfully logged in immediately.</p><p>3- resolve the new response (the one we retry after the user successfully logged in).</p><p>4- pass the <strong>DioUnauthorizedRequestRetrier </strong>error to the handler in case the user is still not <strong>logged in.</strong></p><pre>import &#39;package:famcare/routes/router.dart&#39;;<br><br>import &#39;dio_unauthorized_request_retrier.dart&#39;;<br><br><br>class RetryOnUnauthorizedInterceptor extends Interceptor {<br>  final DioUnauthorizedRequestRetrier requestRetrier;<br><br>  RetryOnUnauthorizedInterceptor({<br>    required this.requestRetrier,<br>  });<br><br>  @override<br>  void onError(DioError err, ErrorInterceptorHandler handler) async {<br>    if (_shouldRetry(err)) {<br>      try {<br>        // open the RegistrationPage.<br>        appRouter.push(const RegistrationPageRoute());<br>        // wati until the requestRetrier retry the request again when user logged in<br>        final response = await requestRetrier.scheduleRequestRetry(<br>          err.requestOptions,<br>          err.response,<br>        );<br>        // resolve the new reponse (after the user logged in).<br>        handler.resolve(response);<br>      } on DioError catch (error) {<br>        // Let any new error from the retrier pass through<br>        handler.next(error);<br>      } catch (error) {<br>        // on unknown error pass the old error<br>        handler.next(err);<br>      }<br>    } else {<br>      handler.next(err);<br>    }<br>  }<br><br>  bool _shouldRetry(DioError error) {<br>    if (error.response == null) return false;<br>    if (error.response?.data == null) return false;<br>    return error.response?.data[&#39;code&#39;] == &#39;anonymous_are_not_allowed&#39;;<br>  }<br>}</pre><h3>Retry on unauthorized Dio Interceptors</h3><p>this code simply</p><p>1- listens to <strong>authStatus stream.</strong></p><p><strong>2- </strong>retry the request when the user<strong> is authenticated.</strong></p><p>3- return the new response.</p><p>4- return the same error if the user is still not <strong>authenticated.</strong></p><pre>import &#39;dart:async&#39;;<br>import &#39;package:dio/dio.dart&#39;;<br><br>class DioUnauthorizedRequestRetrier {<br>  final Dio dio;<br>  final StreamController&lt;bool&gt; authStatus;<br><br>  DioUnauthorizedRequestRetrier({<br>    required this.dio,<br>    required this.authStatus,<br>  });<br><br>  StreamSubscription&lt;bool&gt;? _streamSubscription;<br><br>  Future&lt;Response&gt; scheduleRequestRetry(<br>      RequestOptions requestOptions, Response? errorResponse) async {<br>    final responseCompleter = Completer&lt;Response&gt;();<br><br>    _streamSubscription = authStatus.stream.listen(<br>      (isAuthenticated) async {<br>        _streamSubscription?.cancel();<br>        if (isAuthenticated) {<br>          // Complete the completer instead of returning<br>          responseCompleter.complete(<br>            dio.request(<br>              requestOptions.path,<br>              cancelToken: requestOptions.cancelToken,<br>              data: requestOptions.data,<br>              onReceiveProgress: requestOptions.onReceiveProgress,<br>              onSendProgress: requestOptions.onSendProgress,<br>              queryParameters: requestOptions.queryParameters,<br>              options: Options(<br>                headers: Api.headers(),<br>                method: requestOptions.method,<br>                sendTimeout: AppServiceProvider.sendTimeout,<br>                receiveTimeout: AppServiceProvider.receiveTimeout,<br>              ),<br>            ),<br>          );<br>        } else {<br>          responseCompleter.complete(errorResponse);<br>        }<br>      },<br>    );<br><br>    return responseCompleter.future;<br>  }<br>}</pre><h3><strong>Test the Interceptor and </strong>Request Retrier logic</h3><p>The big question is how to test this logic</p><p>1- each time we need to delete the app to log in <strong>anonymously.</strong></p><p>2- try to use a feature that is not authorized to use without logging in, and make sure the register page is shown on the screen.</p><p>3- create a new account to test the registration flow or login with an old account.</p><p>4- make sure the API is called again and the feature is allowed to use now.</p><p>5- test the scenario when exiting the registration page and make sure the Dio error is passed successfully to the handler and an error message is shown on the screen.</p><p>this will take forever. 😅</p><h3><strong>Unit Test </strong>🤓</h3><p>What about writing a test case for each use case 🫣</p><h4>Test factories and helpers</h4><p>1- Add Dio logger interceptors to help us debug the test</p><p>2- Add retry on unauthorized change interceptor to dio</p><pre>void addDioInterceptors() {<br>    final dio = sl&lt;Dio&gt;();    <br><br>    // add dio logger interceptors to help us debug the test<br>    dio.interceptors.add(PrettyDioLogger());<br><br>    // add retry on unauthorized change interceptor to dio<br>    dio.interceptors.add(<br>      RetryOnUnauthorizedInterceptor(<br>        requestRetrier: DioUnauthorizedRequestRetrier(<br>          dio: dio,<br>          authStatus: appBloc.authStatusStreamController,<br>        ),<br>      ),<br>    );<br>  }</pre><p>just the users who logged in can use the checkout feature, so we decide to test our DOP interceptor on the <strong>initiatePayment</strong> API.</p><p>1- <strong>initialPaymentBody</strong> we send <strong>initiatePayment </strong>API as a request JSON body.</p><p>2- <strong>initialPaymentFailedResponse </strong>is the first response returned from the <strong>initiatePayment</strong> API when the<strong> anonymous user</strong> tries to use features that are not authorized to use without logging in.</p><p>3- <strong>initialPaymentResponse </strong>is the second response returned from the <strong>initiatePayment</strong> API when the user logged in and the <strong>DioUnauthorizedRequestRetrier</strong> retries the API request again.</p><p>4- <strong>newInitialPaymentFailedResponse</strong> is the second response returned from the <strong>initiatePayment</strong> API when the user logged in and the <strong>DioUnauthorizedRequestRetrier</strong> retries the API request again but the <strong>initiatePayment API </strong>returns a new error.</p><pre>final initialPaymentBody = {<br>    &#39;payment_method&#39;: &#39;tabby_installments&#39;,<br>    &#39;cart_id&#39;: &#39;324&#39;,<br>  };<br><br><br>final initialPaymentFailedResponse = ServerExceptionFactory.create(<br>    code: &#39;anonymous_are_not_allowed&#39;,<br>    message: &#39;anonymous_are_not_allowed&#39;,<br>  );<br><br>  <br>final SingleResponse&lt;InitiatePayment&gt; initialPaymentResponse = SingleResponse(<br>    data: InitiatePaymentFactory().create(),<br>  );<br><br><br>final newInitialPaymentFailedResponse = ServerExceptionFactory.create(<br>    code: &#39;coupon_not_allowed&#39;,<br>    message: &quot;الكوبون 40first غير صالح.&quot;,<br>  );</pre><h4>Starting with this use case</h4><blockquote>test anonymous_are_not_allowed api failed should</blockquote><blockquote>retry api again after user logged in</blockquote><blockquote>and return success initialPaymentResponse</blockquote><pre>test(<br>      &#39;test anonymous_are_not_allowed api failed should&#39;<br>      &#39; retry api again after user logged in &#39;<br>      &#39;and return success initialPaymentResponse&#39;, () async {<br>    // given - add dio interceptors<br>    addDioInterceptors();<br><br>    // mock the api call to return anonymous_are_not_allowed failed code this<br>    // should trigger RetryOnUnauthorizedInterceptor and retry the api<br>    // when auth status become true<br>    mockForbiddenPostCall(<br>      url: Api.initiatePayment(),<br>      body: initialPaymentBody,<br>      response: initialPaymentFailedResponse,<br>    );<br><br>    // wait for the api call to be executed, convert the authStatus<br>    // to become true (mock it as user logged in successfully)<br>    // and  mock the api again this time<br>    // to success state<br>    Future.delayed(const Duration(milliseconds: 500), () {<br>      mockPostCall(<br>        url: Api.initiatePayment(),<br>        body: initialPaymentBody,<br>        response: initialPaymentResponse,<br>      );<br>      appBloc.authDirty = true;<br>    });<br><br>    // when - call the initial payment api<br>    final donorsRemoteDataSource = sl&lt;DonorsRemoteDataSource&gt;();<br>    final response = await donorsRemoteDataSource.initiatePayment(<br>      paymentMethod: initialPaymentBody[&#39;payment_method&#39;],<br>      cartID: initialPaymentBody[&#39;cart_id&#39;],<br>    );<br><br>    // then - response must equals the initialPaymentResponse<br>    expect(response, initialPaymentResponse);<br>  });</pre><p>very clean ✌️</p><h4>The second use case</h4><blockquote>test anonymous_are_not_allowed api failed should</blockquote><blockquote>return original api error when user cancel login</blockquote><blockquote>and return initialPaymentFailedResponse</blockquote><pre>  test(<br>      &#39;test anonymous_are_not_allowed api failed should&#39;<br>      &#39; return original api error when user cancel login&#39;<br>      &#39; and return initialPaymentFailedResponse&#39;, () async {<br>    // given - add dio interceptors<br>    addDioInterceptors();<br><br>    // mock the api call to return anonymous_are_not_allowed failed code this<br>    // should trigger RetryOnUnauthorizedInterceptor and retry the api<br>    // when auth status become true<br>    mockForbiddenPostCall(<br>      url: Api.initiatePayment(),<br>      body: initialPaymentBody,<br>      response: initialPaymentFailedResponse,<br>    );<br><br>    // wait for the api call to be executed, convert the authStatus<br>    // to become false (mock it as user cancel login process)<br>    Future.delayed(const Duration(milliseconds: 500), () {<br>      appBloc.authDirty = false;<br>    });<br><br>    // when - call the initial payment api<br>    final donorsRemoteDataSource = sl&lt;DonorsRemoteDataSource&gt;();<br>    try {<br>      await donorsRemoteDataSource.initiatePayment(<br>        paymentMethod: initialPaymentBody[&#39;payment_method&#39;],<br>        cartID: initialPaymentBody[&#39;cart_id&#39;],<br>      );<br>    } catch (e) {<br>      // then - response must equals the initialPaymentFailedResponse<br>      expect(e is ServerException, true);<br>      final serverException = e as ServerException;<br>      expect(<br>        serverException.errors,<br>        initialPaymentFailedResponse.errors,<br>      );<br>      expect(<br>        serverException.statusCode,<br>        initialPaymentFailedResponse.statusCode,<br>      );<br>    }<br>  });</pre><h4>The lase use case</h4><blockquote>test anonymous_are_not_allowed api failed should</blockquote><blockquote>return the new api error</blockquote><blockquote>when initiatePayment api failed again</blockquote><pre>  test(<br>      &#39;test anonymous_are_not_allowed api failed should&#39;<br>      &#39; return  api error when initiatePayment api failed again&#39;, () async {<br>    // given - add dio interceptors<br>    addDioInterceptors();<br><br>    // mock the api call to return anonymous_are_not_allowed failed code this<br>    // should trigger RetryOnUnauthorizedInterceptor and retry the api<br>    // when auth status become true<br>    mockForbiddenPostCall(<br>      url: Api.initiatePayment(),<br>      body: initialPaymentBody,<br>      response: initialPaymentFailedResponse,<br>    );<br><br>    // wait for the api call to be executed, mock api<br>    // again to return new failed message<br>    Future.delayed(const Duration(milliseconds: 500), () {<br>      mockForbiddenPostCall(<br>        url: Api.initiatePayment(),<br>        body: initialPaymentBody,<br>        response: newInitialPaymentFailedResponse,<br>      );<br>      appBloc.authDirty = true;<br>    });<br><br>    // when - call the initial payment api<br>    final donorsRemoteDataSource = sl&lt;DonorsRemoteDataSource&gt;();<br>    try {<br>      await donorsRemoteDataSource.initiatePayment(<br>        paymentMethod: initialPaymentBody[&#39;payment_method&#39;],<br>        cartID: initialPaymentBody[&#39;cart_id&#39;],<br>      );<br>    } catch (e) {<br>      // then - response must equals the initialPaymentFailedResponse<br>      expect(e is ServerException, true);<br>      final serverException = e as ServerException;<br>      expect(<br>        serverException.errors,<br>        newInitialPaymentFailedResponse.errors,<br>      );<br>      expect(<br>        serverException.statusCode,<br>        newInitialPaymentFailedResponse.statusCode,<br>      );<br>    }<br>  });</pre><p>Imagine how many times can run these test cases on every change you do 🥳</p><p>and How much time it will take to finish this task if you rely on your test cases instead of testing them manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Yh4wuIZ-x6Y8HITnqpxPQ.png" /><figcaption>It&#39;s a task of fewer than 3 seconds to run all test cases.</figcaption></figure><h3>Finally 😅</h3><p>Honestly, these test cases saved me from a deadline nightmare 😮‍💨</p><p>Of course, you need to test this feature manually but just once or twice times at the end of the development.</p><p>You will not waste all of your days trying to debug and test this feature by running the whole application on the device and testing all cases.</p><p>Another point these test cases just test the <strong>RetryOnUnauthorizedInterceptor</strong> and the <strong>DioUnauthorizedRequestRetrier</strong> behaviors but for example, these test cases do not check if the registration page will display on the top of the navigation stack or not.</p><p>Maybe some methods like <strong>mockPostCall</strong> and <strong>mockForbiddenPostCall</strong> are mysterious to you on my next article I will explain what is these methods and how we test our data layer easily.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2795867bbff" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power of the Swift extensions with type constraints]]></title>
            <link>https://medium.com/@salahamassi/power-of-the-swift-extensions-with-type-constraints-97b1c8a4536e?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97b1c8a4536e</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[protocol]]></category>
            <category><![CDATA[extension]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 18:54:57 GMT</pubDate>
            <atom:updated>2025-06-09T00:07:47.616Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jPvge3t6u5lFeZkSi5L0NA.png" /></figure><p>A long time ago, I did not write any Swift code because I was busy with other projects that depend on the Flutter technology. Recently, I went back to writing some Swift code for a previous project.</p><pre>animate action button above the keyboard.<br><br>func addKeyboardObservers() {<br>    NotificationCenter.default.addObserver(<br>        self,<br>        selector: #selector(keyboardWillShowNotification),<br>        name: UIResponder.keyboardWillShowNotification,<br>        object: nil<br>    )<br>    <br>    NotificationCenter.default.addObserver(<br>        self,<br>        selector: #selector(keyboardWillHideNotification),<br>        name: UIResponder.keyboardWillHideNotification,<br>        object: nil<br>    )<br>}<br><br>@objc<br>private func keyboardWillShowNotification(notification: Notification) {<br>    handleKeyboardNotification(notification, WillShow: true)<br>}<br><br>@objc<br>private func keyboardWillHideNotification(notification: Notification) {<br>    handleKeyboardNotification(notification, WillShow: false)<br>}<br><br>private func handleKeyboardNotification(_ notification: Notification, WillShow: Bool) {<br>    guard let userInfo = notification.userInfo,<br>          let keyboardFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue,<br>          let animationDuration = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue,<br>          let animationCurve = (userInfo[UIResponder.keyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue,<br>          let stackView = actionButton.superview as? UIStackView,<br>          let footerView = stackView.superview?.superview as? UIStackView<br>    else { return }<br>    let firstView = footerView.arrangedSubviews[0]<br>    let lastView = footerView.arrangedSubviews[1]<br>    <br>    var safeAreaInsetsBottom = view.safeAreaInsets.bottom<br>    safeAreaInsetsBottom = safeAreaInsetsBottom == 0 ? 0 : safeAreaInsetsBottom - 20<br>    if WillShow {<br>        footerView.transform = .init(translationX: 0, y: -(keyboardFrame.height - safeAreaInsetsBottom))<br>    } else {<br>        footerView.transform = .identity<br>    }<br>    <br>    UIView.animate(<br>        withDuration: animationDuration,<br>        delay: 0,<br>        options: [UIView.AnimationOptions(rawValue: animationCurve)],<br>        animations: {<br>            [firstView, lastView].forEach {<br>                $0.alpha = WillShow ? 0 : 1<br>            }<br>            stackView.withMargins(<br>                WillShow<br>                ? .init(<br>                    top: .zero,<br>                    left: .zero,<br>                    bottom: safeAreaInsetsBottom,<br>                    right: 0<br>                )<br>                : .init(<br>                    top: 15,<br>                    left: 15,<br>                    bottom: 20,<br>                    right: 15<br>                )<br>            )<br>            continueButton.withCornerRadius(WillShow ? .zero : 8)<br>            <br>            self.view.layoutIfNeeded()<br>        },<br>        completion: nil<br>    )<br>}</pre><p>When I noticed that this code was repeated in many View Controllers and I will repeat it more in the coming days, I decided to do a simple refactor and move all this code somewhere.</p><p>This code will just move the footer view to be above the keyboard when the keyboard appears, and back to normal when the keyboard disappears</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*V-pGtyYoeFLZVUUXHZZhUQ.gif" /></figure><h3><strong>UIViewController extension</strong></h3><p>The first thing that comes to my head is to move all this logic to an UIViewController extension</p><pre>extension UIViewController {<br><br>    func addKeyboardObservers() { .. }<br><br>    private func handleKeyboardNotification(_ notification: Notification, WillShow: Bool)  { .. }<br><br>    @objc<br>    private func keyboardWillShowNotification(notification: Notification) { .. }<br><br>    @objc<br>    private func keyboardWillHideNotification(notification: Notification) { .. }<br>}</pre><p>but I faced some obstacles</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ykP4Jn4xpptws8P5xoZ_PQ.png" /><figcaption>Cannot find ‘actionButton’ in scope</figcaption></figure><p>The action button is a property related to a specific view controller so we need to find a way to retrieve it from any view controller that wants to have this cool animation</p><h3>HasActionButton protocol</h3><p>the second idea that comes to my head is to create a new protocol called <strong>HasActionButton</strong> and any view controller who wants to have this animation must confirm this protocol requirement</p><pre>protocol HasActionButton {<br>    <br>    var actionButton: UIButton { get }<br>    <br>}</pre><p>now any view controller can confirm this protocol and define the <strong>actionButton</strong> property</p><pre>extension CustomerSigninViewController: HasActionButton {<br>    var actionButton: UIButton {<br>        signinButton<br>    }<br>}</pre><h3><strong>Back to our extension</strong></h3><p>until now our extension will still complain from the same error <strong>Cannot find ‘actionButton’ in scope</strong></p><p>we need to extend our new protocol <strong>HasActionButton not the </strong>UIViewController and put<strong> </strong>constraints on this extension to make these functions are just available for UIViewController subclasses</p><p>that means this extension functionality is just available for the views controller who confirms the <strong>HasActionButton</strong> protocol</p><pre>public extension HasActionButton where Self: UIViewController {<br><br>    func addKeyboardObservers() { .. }<br><br>    private func handleKeyboardNotification(_ notification: Notification, WillShow: Bool)  { .. }<br><br>    @objc<br>    private func keyboardWillShowNotification(notification: Notification) { .. }<br><br>    @objc<br>    private func keyboardWillHideNotification(notification: Notification) { .. }<br>}</pre><h3>Last problem (@objc selectors)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UZaCkKBFCV36l9c1e8aZTw.png" /><figcaption>@objc can only be used with members of classes, @objc protocols, and concrete extensions of classes</figcaption></figure><p>as the text of the problem shows the @objc selector can just be used with members of classes @objc protocols and concrete extensions of classes</p><p>we can define any @objc selector inside any class we want like ViewController class’s</p><p>or inside the concrete extensions of these classes like a direct extension to UIViewController</p><p>a simple solution for this problem is to use another method to add a notification observer without selectors</p><pre>func addKeyboardObservers() {<br>    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillShowNotification,<br>                                           object: nil,<br>                                           queue: nil) { [weak self] (notification) in<br>        guard let self = self else { return }<br>        self.handleKeyboardNotification(notification, WillShow: true)<br>    }<br><br>    NotificationCenter.default.addObserver(forName: UIResponder.keyboardWillHideNotification,<br>                                           object: nil,<br>                                           queue: nil) { [weak self] (notification) in<br>        guard let self = self else { return }<br>        self.handleKeyboardNotification(notification, WillShow: false)<br>    }<br>}</pre><h3>End Of The Story ✌🏽</h3><p>just that it is now for every view controller to use this feature just confirm the <strong>HasActionButton </strong>protocol and call <strong>addKeyboardObservers</strong> method.</p><pre><br>class SigninViewController: UIViewController {<br><br>    @IBOutlet weak var mobileTextField: WinchTextFieldView!<br>    @IBOutlet weak var signinButton: UIButton!<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        addKeyboardObservers()<br>    }<br>}<br><br>extension SigninViewController: ActionableFooter {<br>    var actionButton: UIButton {<br>        signinButton<br>    }<br>}</pre><p>✌🏽</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97b1c8a4536e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stretchy Header Collection View with images slider]]></title>
            <link>https://medium.com/@salahamassi/stretchy-header-collection-view-with-images-slider-8202a56b3cbf?source=rss-7b866121344a------2</link>
            <guid isPermaLink="false">https://medium.com/p/8202a56b3cbf</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uicollectionviewlayout]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[Salah Nahed]]></dc:creator>
            <pubDate>Sun, 03 Jul 2022 08:15:01 GMT</pubDate>
            <atom:updated>2025-06-09T00:04:13.364Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nQOBMrK_-iFrjpquMxMlw.png" /></figure><p>We can add a Stretchy Hader view for the collection view simply using “SupplementaryView”. <br>we can achieve this using custom “UICollectionViewFlowLayout” and use the “layoutAttributesForElements” method to update attribute frames based on scroll content offset y.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d100595fe2d3e8f350077787e0ed312/href">https://medium.com/media/9d100595fe2d3e8f350077787e0ed312/href</a></iframe><p>[Full implementation here](<a href="https://medium.com/@mail2ashislaha/stretchy-header-animation-using-collection-view-custom-layout-f2ce466ec710">https://medium.com/@mail2ashislaha/stretchy-header-animation-using-collection-view-custom-layout-f2ce466ec710</a>)</p><p>But what if we need to add a collection view inside the header view?</p><p>The client wants to replace the fixed product image with an array of products images, so we need to remove the image view and add a collection view with images cells</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d40415d779d46f6535f724b1ae6144d6/href">https://medium.com/media/d40415d779d46f6535f724b1ae6144d6/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9cba581680b7f2014e6a2ce34908c404/href">https://medium.com/media/9cba581680b7f2014e6a2ce34908c404/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c7c2867ad4a8ec10328489b8c13d18c/href">https://medium.com/media/3c7c2867ad4a8ec10328489b8c13d18c/href</a></iframe><p>If you try that unfortunately you will end up with this weird behavior</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*bvGeiw7W8zAom8Xv.gif" /></figure><p>Instead of this normal one</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/0*-_TYYaHE4LU4gMZx.gif" /></figure><p>And of course, you will find the console starts screaming with warnings.</p><p>The problem is when we update the layout attribute frame for the header view this will update the collection view frame (the one inside the header view), but not the image cells.</p><p>so when we are scrolling we see the blue color (the background color for the collection view inside the header view) and not the image cell color.</p><p>we need to notify the header collection view to update the size for his cells at the same time when we update the layout attribute frame for the header view itself. and we can do that simply using</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc420c87d2ff4a5c8f6e6eb0950515e6/href">https://medium.com/media/dc420c87d2ff4a5c8f6e6eb0950515e6/href</a></iframe><p>this will invoke all the “UICollectionViewDelegateFlowLayout” methods and the size will be updated.</p><p>So one solution we can do is have closure on our custom flow layout class and we can invoke this closure when we update the header layout attribute frame.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97477f3e0bbcf1405ae056b7346ae95e/href">https://medium.com/media/97477f3e0bbcf1405ae056b7346ae95e/href</a></iframe><p>The client (the view controller in our case) can use this closure like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e06d95ab71e4c6447d1146f2dd3b5d9/href">https://medium.com/media/2e06d95ab71e4c6447d1146f2dd3b5d9/href</a></iframe><p>Now everything will work smoothly. 🚀</p><p>you can run the full project from here:</p><p><a href="https://github.com/salahamassi/Stretchy-Header-Collection-View">GitHub - salahamassi/Stretchy-Header-Collection-View</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8202a56b3cbf" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>