<?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 Giulio Caggegi on Medium]]></title>
        <description><![CDATA[Stories by Giulio Caggegi on Medium]]></description>
        <link>https://medium.com/@giulio.caggegi?source=rss-c1fc89daa3f7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*yjaZbDVBVoW3I5xEW_yF3g.jpeg</url>
            <title>Stories by Giulio Caggegi on Medium</title>
            <link>https://medium.com/@giulio.caggegi?source=rss-c1fc89daa3f7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 09:01:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@giulio.caggegi/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[Actors vs Mutexes: Or How I Stopped Worrying and Let the Compiler Yell at Me]]></title>
            <link>https://medium.com/@giulio.caggegi/actors-vs-mutexes-or-how-i-stopped-worrying-and-let-the-compiler-yell-at-me-a00e82cf95eb?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/a00e82cf95eb</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Wed, 24 Dec 2025 15:02:42 GMT</pubDate>
            <atom:updated>2025-12-24T15:02:42.658Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*1hZq7oGn6K1Klmul" /><figcaption>Photo by <a href="https://unsplash.com/@flyd2069?utm_source=medium&amp;utm_medium=referral">FlyD</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Concurrency bugs are fascinating.</p><p>They tend to disappear in debug builds and reappear right after you hit “Release”.</p><p>They disappear when you add logs, reappear in production, and only affect one specific user, on one specific device, at 3 a.m.</p><p>For years, we’ve tried to tame them with mutexes.</p><p>Then actors showed up and said:</p><blockquote>What if… you just weren’t allowed to do the wrong thing?</blockquote><p>Let’s talk about it, with a real iOS example.</p><h3>The classic mutex approach (aka “I promise this is safe”)</h3><p>Imagine a very common scenario: an App Settings or Session store shared across the app.</p><h3>Mutex-based implementation</h3><pre>final class SessionStore {<br>    private var sessionId: String?<br>    private let lock = NSLock()<br><br>    func setSessionId(_ id: String?) {<br>        lock.lock()<br>        sessionId = id<br>        lock.unlock()<br>    }<br><br>    func getSessionId() -&gt; String? {<br>        lock.lock()<br>        let id = sessionId<br>        lock.unlock()<br>        return id<br>    }<br>}</pre><p>Until:</p><ul><li>someone forgets to lock</li><li>someone adds early returns</li><li>someone calls it from a background queue they swore was safe</li><li>someone refactors it six months later (that someone is you)</li></ul><p>This works only as long as every developer behaves perfectly.</p><p>The compiler is silent.</p><p>The runtime is silent.</p><p>Production is not.</p><h3>The actor version (aka “No, you can’t do that”)</h3><p>Now let’s rewrite the same thing using an actor.</p><pre>actor SessionStore {<br>    private var sessionId: String?<br><br>    func setSessionId(_ id: String?) {<br>        sessionId = id<br>    }<br><br>    func getSessionId() -&gt; String? {<br>        sessionId<br>    }<br>}</pre><p>That’s it. No locks, no queues, no conventions written in a README nobody reads.</p><p>Usage:</p><pre>let store = SessionStore()<br><br>await store.setSessionId(&quot;abc123&quot;)<br>let id = await store.getSessionId()</pre><p>If you try to:</p><ul><li>access sessionId directly</li><li>call methods without await</li><li>mutate state from outside</li></ul><p>The compiler <strong>stops</strong> you.</p><p>Not a warning, an <strong>error</strong>.</p><h3>“But async/await everywhere is annoying”</h3><p>Yes, so are data races.</p><p>Actors force you to acknowledge something important:</p><blockquote>Accessing shared mutable state is not free.</blockquote><p>Mutexes hide that cost, Actors make it explicit.</p><p>That’s a feature, not a drawback.</p><h4>So… should we throw mutexes away?</h4><p>No, but we should stop using them as a default.</p><h3>Mutexes are great when</h3><ul><li>writing low-level primitives</li><li>performance is critical and measured</li><li>async/await is not an option</li><li>you fully control the threading model</li></ul><h3>Actors are great when</h3><ul><li>modeling business logic</li><li>owning state</li><li>writing SDKs or app-level services</li><li>correctness matters more than cleverness</li></ul><p>Most app code falls into the second category.</p><h3>The real difference (spoiler: it’s not performance)</h3><p>Mutexes say:</p><blockquote>You can do anything. Please be careful.</blockquote><p>Actors say:</p><blockquote>You can’t do that.</blockquote><blockquote>And no, I don’t care that it usually works.</blockquote><p>One relies on discipline, the other relies on the type system.</p><p>I know which one I trust more at 3 a.m.</p><h3>Final thought</h3><p>Actors didn’t replace mutexes.</p><p>They replaced:</p><ul><li>tribal knowledge</li><li>comments like “must be called on this queue”</li><li>concurrency bugs that only reproduce once a month</li></ul><p>If you’re writing modern Swift and asking:</p><blockquote>What should I use by default?</blockquote><p>Start with actors, reach for mutexes only when you must.</p><p>Your future self will thank you; probably silently. At least without crashes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a00e82cf95eb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AsyncStreamSignal in Swift: Streams for Everyone ]]></title>
            <link>https://medium.com/@giulio.caggegi/asyncstreamsignal-in-swift-streams-for-everyone-bbe3df3345ae?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbe3df3345ae</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Fri, 02 May 2025 11:25:27 GMT</pubDate>
            <atom:updated>2025-05-02T11:25:27.619Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Hx7c0JufmaR6kUYhkeRFew@2x.jpeg" /></figure><p>Imagine you want to send signals around. Now, you could use AsyncStream, but there&#39;s a catch: <strong>only one</strong> listener allowed. First come, first served.</p><p>But what if you want to talk to a whole crowd instead of whispering to one person?</p><p>Meet AsyncStreamSignal, your new best friend for broadcasting values to multiple listeners, without breaking a sweat (or the concurrency model).</p><h3>Why AsyncStreamSignal?</h3><p>Because AsyncStream is like a one-on-one conversation. Sometimes you want a group call. Or a town hall meeting.</p><p>With AsyncStreamSignal:</p><ul><li>Each listener gets its own independent AsyncStream</li><li>Every listener receives <strong>every</strong> emitted value</li><li>When a listener leaves (cancels their stream), they get removed cleanly</li></ul><p>No drama. No mess.</p><h3>The Magic</h3><p>Here’s the core idea:</p><pre>actor AsyncStreamSignal&lt;T&gt; {<br>    private var continuations: [(id: UUID, continuation: AsyncStream&lt;T&gt;.Continuation)] = []<br><br>    func stream() -&gt; AsyncStream&lt;T&gt; {<br>        AsyncStream { continuation in<br>            let id = UUID()<br>            continuations.append((id, continuation))<br>            <br>            continuation.onTermination = { @Sendable _ in<br>                Task { await self.remove(id: id) }<br>            }<br>        }<br>    }<br><br>    func send(_ value: T) {<br>        for (_, continuation) in continuations {<br>            continuation.yield(value)<br>        }<br>    }<br><br>    func finish() {<br>        for (_, continuation) in continuations {<br>            continuation.finish()<br>        }<br>        continuations.removeAll()<br>    }<br><br>    private func remove(id: UUID) {<br>        continuations.removeAll { $0.id == id }<br>    }<br>}<br><br>extension AsyncStreamSignal where T == Void {<br>    func send() {<br>        for (_, continuation) in continuations {<br>            continuation.yield(())<br>        }<br>    }<br>}</pre><h3>How It Works (Without The Boring Bits)</h3><ul><li>stream() hands you a fresh new AsyncStream each time</li><li>send(value) pushes the value to <strong>all</strong> active listeners</li><li>finish() wraps it all up nicely when it&#39;s time to go home</li><li>If someone unsubscribes, they’re quietly removed. No need for goodbyes.</li></ul><p>And yes, it’s an actor. Because Swift Concurrency demands respect.</p><h3>How to use it</h3><pre>struct ContentView: View {<br>    <br>    @Injected let signal:AsyncStreamSignal&lt;Int&gt;<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Hello, AsyncStreamSignal!&quot;)<br>        }<br>        .padding()<br>        .onAppear {<br>            Task {<br>                try await Task.sleep(for: .seconds(2))<br>                await signal.send(Int.random(in: 0..&lt;100))<br>                try await Task.sleep(for: .seconds(1))<br>                await signal.send(Int.random(in: 0..&lt;100))<br>                try await Task.sleep(for: .seconds(1))<br>                await signal.finish()<br>            }<br>        }<br>        .task {<br>            Task {<br>                for await value in await signal.stream() {<br>                    print(&quot;Task A received signal with value \(value)!&quot;)<br>                }<br>                print(&quot;Task A: stream closed&quot;)<br>            }<br><br>            Task {<br>                for await value in await signal.stream() {<br>                    print(&quot;Task B received signal with value \(value)!&quot;)<br>                }<br>                print(&quot;Task B: stream closed&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Bonus: Void Signals</h3><p>Sometimes you just want to shout “Hey!” without carrying a message. For those moments:</p><pre>signal.send()</pre><p>Clean, empty, beautiful.</p><h3>When Should You Use AsyncStreamSignal?</h3><ul><li>Broadcasting system events (“user logged out”, “connection lost”)</li><li>Internal app notifications without tying yourself to NotificationCenter</li><li>Lightweight reactive architectures without pulling in Combine, RxSwift, etc.</li><li>Dispatching triggers across different layers of your app</li></ul><p>Anytime you want <strong>multiple listeners</strong> to stay in sync with <strong>minimal ceremony</strong>.</p><h3>How Is This Different From Combine?</h3><p>Good question.</p><p>Combine is a <strong>full-blown reactive framework</strong>. It brings:</p><ul><li>Publishers</li><li>Subscribers</li><li>Operators (map, filter, debounce, etc.)</li><li>Error handling</li><li>Complex pipelines</li></ul><p>It’s powerful, but sometimes… <strong>you don’t need all that</strong>.</p><p>AsyncStreamSignal is:</p><ul><li>Tiny</li><li>Purpose-built for simple broadcasting</li><li>No dependencies</li><li>Native async/await style</li><li>Zero operators to learn</li></ul><p>If Combine is a massive concert hall with sound engineering, AsyncStreamSignal is you standing on a chair shouting “Pizza’s here!”. And sometimes that’s exactly what you want.</p><h3>Final Thoughts</h3><p>AsyncStreamSignal is like running a cozy live show in your app: every guest has front-row seats, and nobody misses a beat.</p><p>And the best part?</p><ul><li>Tiny footprint</li><li>Fully Swift-native</li><li>Zero dependencies</li><li>Friendly with async/await</li></ul><p>If you’re tired of cobbling together your own broadcast systems, give AsyncStreamSignal a spin.</p><p>P.S. If you’ve been abusing NotificationCenter out of frustration... you really deserve this upgrade.</p><p>Happy streaming! 🎶</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbe3df3345ae" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring the Mysteries of SPM (Swift Package Manager) — A Journey of Scope, Cache, and Registry…]]></title>
            <link>https://medium.com/@giulio.caggegi/exploring-the-mysteries-of-spm-swift-package-manager-a-journey-of-scope-cache-and-registry-6d7bf547f6cf?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/6d7bf547f6cf</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Sun, 23 Mar 2025 18:07:08 GMT</pubDate>
            <atom:updated>2025-03-23T18:56:19.413Z</atom:updated>
            <content:encoded><![CDATA[<h3>Exploring the Mysteries of SPM (Swift Package Manager) — A Journey of Scope, Cache, and Registry Chaos</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yGaIzbz7gyfsS6Xx" /><figcaption>Photo by <a href="https://unsplash.com/@klerwonder?utm_source=medium&amp;utm_medium=referral">Klára Vernarcová</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’ve ever spent a sleepless night tangled in the ever-growing vines of dependency management, congratulations! You are officially a developer. Today, we’re diving into the shadowy depths of SPM — Swift Package Manager — and uncovering all the weird quirks that might leave you wondering if someone up there just enjoys messing with us.</p><h3>What is SPM and Why Should You Care?</h3><p>Swift Package Manager (SPM) is Apple’s officially blessed tool for dependency management and the building, testing, and distribution of Swift packages. Think of it as the Xcode Command Line Tool’s younger, cooler sibling. But what makes SPM special is its tight integration with Xcode and its open-source nature. It’s designed to handle the following:</p><ul><li>Declaring packages and their dependencies via Package.swift files.</li><li>Resolving version dependencies automatically.</li><li>Building source code modules into dynamic or static libraries.</li><li>Generating Xcode projects for those who like clicking buttons instead of typing commands.</li></ul><p>Unlike CocoaPods or Carthage, SPM doesn’t rely on a centralized server. Instead, it works directly with Git repositories. But then came the introduction of Package Registries…</p><h3>Registries vs. Repositories</h3><p>Registries and repositories serve different purposes in the SPM ecosystem. Before registries existed, SPM was a simple Git-based system. You’d point it to a repo URL, specify a version tag, and off you go. But as things scaled up, Apple introduced Package Registries with Swift 5.6 to provide a more robust package distribution mechanism.</p><h3>Registries</h3><p>A Registry acts as a formal index that maps package names to their actual URLs. Think of it as a directory service where packages are cataloged, providing a consistent naming convention and enabling authenticated access. This setup becomes essential when you’re dealing with enterprise-level dependencies.</p><p>Registries are useful because they:</p><ul><li>Improve reproducibility by ensuring that package versions are immutable.</li><li>Provide more efficient downloads via pre-packaged archives instead of cloning entire git repositories.</li><li>Support authentication mechanisms for private packages.</li><li>Allow hosting of multiple packages under the same scope, giving more structure and control.</li></ul><p>When you use the command:</p><pre>swift package-registry set &lt;registry-url&gt;</pre><p>SPM creates or updates a JSON file at ~/.swiftpm/configuration/registries.json or ./.swiftpm/configuration/registries.json (per project) to store registry configurations.</p><p>Example of registries.json:</p><pre>{<br>  &quot;registries&quot;: {<br>    &quot;acme&quot;: {<br>      &quot;url&quot;: &quot;https://registry.acme-inc.test&quot;<br>    },<br>    &quot;mycompany&quot;: {<br>      &quot;url&quot;: &quot;https://registry.mycompany.com&quot;<br>    }<br>  },<br>  &quot;version&quot;: 1<br>}</pre><p>This JSON shows two configured registries: acme and mycompany. Each registry has its URL, which SPM uses to communicate with that specific registry.</p><h3>Understanding Scopes and Why They Matter</h3><p>Scopes are a fundamental part of package registries in SPM, but they’re configured separately from the registries themselves. They act as namespaces that allow multiple packages to be organized logically under a single umbrella. For example, <em>MyCompany.MyLibrary</em> and <em>MyCompany.AnotherLibrary</em> share the same scope <em>MyCompany</em>.</p><p>Scopes are useful because:</p><ul><li>They prevent name collisions between packages.</li><li>They allow organizations to group related packages under a common name.</li><li>They dictate how packages are mapped to registries when configured.</li><li>They are case-insensitive, so MyCompany and mycompany are treated as the same.</li></ul><p>After configuring your registries, you’ll need to set up which scopes are associated with which registries. This mapping tells SPM where to look for packages with specific scopes.</p><h3>Authentication and Credentials Management</h3><p>When logging into a private registry:</p><pre>swift package-registry login &lt;registry-url&gt;</pre><p>SPM will prompt you to provide a token. The credentials will be stored securely in your Keychain (macOS) or ~/.netrc (Linux/Windows). If you specify --login &lt;username&gt;, this will be saved in the registries.json file, but not the token itself.</p><h3>Publishing Multiple Libraries Under the Same Scope</h3><p>Let’s say you want to create multiple libraries under the same scope. Each library should be in its own repository or package directory with its own Package.swift file. The structure should look something like:</p><pre>SPM Unified Repository<br>├── MyCompany<br>│   ├── LibraryOne<br>│   │   ├── Package.swift<br>│   │   └── Sources/<br>│   │       └── ...<br>│   └── LibraryTwo<br>│       ├── Package.swift<br>│       └── Sources/<br>│           └── ...</pre><p>When publishing these packages to your registry, they’ll all share the <em>“MyCompany”</em> scope but will be separate packages. Make sure to configure your registry to recognize this scope for proper resolution.</p><h3>Example of a Normal Swift Package</h3><pre>// swift-tools-version:5.7<br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;MyLibrary&quot;,<br>    platforms: [.iOS(.v13)],<br>    products: [<br>        .library(name: &quot;MyLibrary&quot;, targets: [&quot;MyLibrary&quot;])<br>    ],<br>    dependencies: [<br>        .package(name: &quot;DependencyA&quot;, url: &quot;https://github.com/YourOrg/DependencyA.git&quot;, from: &quot;1.0.0&quot;)<br>    ],<br>    targets: [<br>        .target(<br>            name: &quot;MyLibrary&quot;,<br>            dependencies: [&quot;DependencyA&quot;]<br>        ),<br>        .testTarget(<br>            name: &quot;MyLibraryTests&quot;,<br>            dependencies: [&quot;MyLibrary&quot;]<br>        )<br>    ]<br>)</pre><p>This is a typical example of a Swift package that uses a normal target referencing dependencies directly. Note that “DependencyA” in the target dependencies refers to the external package declared in the dependencies array. This works perfectly for non-binary targets.</p><h3>Binary Target with Dependencies, your final Boss</h3><p>When you publish a <em>binaryTarget</em> with dependencies, SPM does not automatically recognize the dependencies unless they are explicitly declared and imported by some source file.</p><p>The problem is that SPM expects every dependency to be referenced in a target, otherwise it will not include them in the build process.</p><p>Moreover, SPM does not supplies an API to declare dependencies for a binary target.</p><p>This is where the Wrapper Target trick comes in.</p><h4>What Happens Without the Wrapper Target</h4><p>If you try to build or publish your binary target without declaring the dependencies properly, you may encounter errors like:</p><ul><li>module not found</li><li>unresolved dependency</li><li>Incomplete linkage at runtime if the dependencies are dynamically linked.</li></ul><h4>The Solution: Wrapper Target</h4><p>The trick is to create a target that simply imports the needed dependencies without actually using them. This forces SPM to recognize the dependencies and include them during the build process.</p><pre>// swift-tools-version:5.7<br>import PackageDescription<br><br>let package = Package(<br>    name: &quot;MyBinaryPackage&quot;,<br>    platforms: [.iOS(.v13)],<br>    products: [<br>        .library(<br>            name: &quot;MyBinaryPackage&quot;,<br>            targets: [&quot;MyBinaryPackage&quot;, &quot;MyBinaryPackageWrapperTarget&quot;]),<br>    ],<br>    dependencies: [<br>        .package(name: &quot;DependencyA&quot;, url: &quot;https://github.com/YourOrg/DependencyA.git&quot;, from: &quot;1.0.0&quot;),<br>        .package(name: &quot;DependencyB&quot;, url: &quot;https://github.com/YourOrg/DependencyB.git&quot;, from: &quot;1.0.0&quot;)<br>    ],<br>    targets: [<br>        .binaryTarget(<br>            name: &quot;MyBinaryTarget&quot;,<br>            path: &quot;./path/to/MyBinary.xcframework&quot;<br>        ),<br>        .target(<br>            name: &quot;MyBinaryPackageWrapperTarget&quot;,<br>            dependencies: [.product(name: &quot;DependencyA&quot;), .product(name: &quot;DependencyB&quot;)],<br>            path: &quot;./WrapperTargetPath&quot;<br>        )<br>    ]<br>)</pre><p>Note that in your ‘WrapperTarget’ path there must be a dummy file, even if empty; otherwise, SPM will not recognize your folder as a target.</p><h4>Digging Through Cache and JSON Files</h4><p>When SPM caches registries and dependencies, it creates JSON files in:</p><ul><li>~/Library/Caches/org.swift.swiftpm/ (Cache file)</li><li>~/Library/org.swift.swiftpm/ (Registries and fingerprints)</li></ul><p>These files provide details about registered registries, scopes, and security settings. If you’re troubleshooting SPM issues, these are the digital rabbit holes you’ll need to explore.</p><h3>Final Thoughts</h3><p>Swift Package Manager is like a powerful magical tool: once you master the subtleties of registries, scopes, and configurations, it opens up a world of possibilities for managing dependencies with elegance. It might seem complex at first, but remember: every SPM expert started exactly where you are now. So explore, experiment, and above all, enjoy the journey through the wonderful Swift ecosystem. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6d7bf547f6cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unchain Your Data: Use SwiftData Without SwiftUI]]></title>
            <link>https://medium.com/@giulio.caggegi/unchain-your-data-use-swiftdata-without-swiftui-ed7b7abe3a6f?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed7b7abe3a6f</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Fri, 13 Dec 2024 17:02:16 GMT</pubDate>
            <atom:updated>2024-12-13T17:02:16.842Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>SwiftData Unplugged: No SwiftUI, No Limits</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XHWhSpdE9nCB2TvF" /><figcaption>Photo by <a href="https://unsplash.com/@abject?utm_source=medium&amp;utm_medium=referral">benjamin lehman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4><strong>Introduction</strong></h4><p><strong>SwiftData and SwiftUI are often seen as inseparable — but they don’t have to be.</strong> While the typical approach relies on <em>@Environment(\.modelContext)</em>, this limits your logic to SwiftUI views. But what if you need to write background tasks, framework logic, or a standalone persistence layer?</p><p><strong>Good news</strong> — you can detach SwiftData from SwiftUI and use it independently. No @Environment, no @View, and no SwiftUI dependencies. In this guide, you’ll learn how to do it in a clean, testable, and maintainable way.</p><p><strong>Why Separate SwiftData From SwiftUI?</strong></p><p>Before we get into the details, let’s discuss <strong>why you might want to separate SwiftData from SwiftUI</strong>. Here are some good reasons:</p><p>• <strong>Architecture</strong>: Services, repositories, and other core logic shouldn’t depend on SwiftUI.</p><p>• <strong>Reusability</strong>: If you plan to use SwiftData logic in multiple apps or modules, you don’t want to drag along SwiftUI.</p><p>• <strong>Testability</strong>: Decoupling from SwiftUI makes it easier to test persistence logic in isolation.</p><p>• <strong>Flexibility</strong>: You can run the logic in <strong>background tasks</strong> or <strong>unit tests</strong> without needing a SwiftUI view.</p><p>If these reasons sound familiar, then you’re in the right place.</p><h4><strong>How It’s Usually Done</strong></h4><p>If you’ve been following the typical <strong>SwiftData + SwiftUI</strong> approach, you might see something like this:</p><pre>NavigationStack {<br>...<br>}<br>.modelContainer(for: [MyModel.self])</pre><pre>struct ContentView: View {<br>  @Query(sort: \MyModel.name) var myModels: [MyModel]<br>  @Environment(\.modelContext) var modelContext<br>  <br>  var body: some View {<br>    Button(&quot;Add Item&quot;) {<br>      let item = MyModel(name: &quot;New Item&quot;)<br>      modelContext.insert(item)<br>      try? modelContext.save()<br>    }<br>  }<br>}</pre><p>This approach is fine if you live in <strong>View-Land</strong>, but what happens if you want to call<strong> </strong><em>modelContext</em><strong> from a service layer</strong>? You can’t. Or maybe yes…</p><h4><strong>How to Detach SwiftData From SwiftUI</strong></h4><p>Here’s a simple <strong>Service</strong> that works as a persistence layer. It’s a <strong>clean, testable implementation</strong> of a service that adds, deletes, and fetches items from <strong>SwiftData</strong>.</p><pre>import Foundation<br>import SwiftData<br><br>struct MyService: MyServiceProtocol {<br>    <br>    // MARK: - Stored Properties<br>    <br>    /// The `ModelContainer`.<br>    private var modelContainer: ModelContainer<br>    <br>    // MARK: - Computed Properties<br>    <br>    /// The `ModelContext`.<br>    private var modelContext: ModelContext { modelContainer.mainContext }<br>    <br>    // MARK: - Init<br>    <br>    init(modelContainer: ModelContainer) {<br>      self.modelContainer = modelContainer<br>    }<br>    <br>    // MARK: - MyServiceProtocol<br>    <br>    func add(_ model: MyModel) throws {<br>      modelContext.insert(model)<br>      try modelContext.save()<br>    }<br>    <br>    func delete(_ id: UUID) throws {<br>      try modelContext.delete(model: MyModel.self, where: #Predicate&lt;MyModel&gt; {<br>        $0.id == id<br>      })<br>      try modelContext.save()<br>    }<br>    <br>    ...<br>  }</pre><p>The <em>ModelContainer</em> is built in this way:</p><pre>var container: ModelContainer = {<br>  let config = ModelConfiguration(cloudKitDatabase: .none) // or whatever you want for `cloudKitDatabase`<br>  return try ModelContainer(for: MyModel.self, configurations: config)<br>}()</pre><h3><strong>Final Thoughts</strong></h3><p>Separating <strong>SwiftData</strong> from <strong>SwiftUI</strong> is absolutely possible. You can achieve a decoupled, testable, and highly reusable persistence layer.</p><p>No more <strong>@Environment</strong>. No more <strong>actor-isolation errors</strong>. No more <strong>SwiftUI view dependencies</strong>. Just clean, modular, and modern Swift. Enjoy yourself and let’s make <strong>SwiftData</strong> truly universal.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed7b7abe3a6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Excluding Files from iCloud Backups in iOS]]></title>
            <link>https://medium.com/@giulio.caggegi/excluding-files-from-icloud-backups-in-ios-78f3c64f26da?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/78f3c64f26da</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Sat, 12 Oct 2024 08:41:05 GMT</pubDate>
            <atom:updated>2024-10-12T08:41:05.127Z</atom:updated>
            <content:encoded><![CDATA[<h4>The Nitty-Gritty You Didn’t Know You Needed</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*VjCssllRzWwQ3Hi6" /><figcaption>Photo by <a href="https://unsplash.com/@siyuan_hu?utm_source=medium&amp;utm_medium=referral">Siyuan Hu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you’re anything like me, you’ve probably spent countless hours questioning life’s greatest mysteries: What’s the meaning of life? How do I avoid iCloud backup bloat? I can’t help much with the first one, but for the second, I’ve got you covered.</p><p>Let’s talk about something not-so-glamorous but incredibly useful for iOS developers: excluding files from iCloud backups. Why? Because no one likes clutter. And trust me, that massive database file doesn’t need to follow your users around every time they set up a new device. Unless, of course, they find joy in restoring unnecessary data (spoiler: they don’t).</p><h4>The problem</h4><p>iOS backups are fantastic. But when you’re dealing with large databases, cache files, or temporary assets that your app needs for the here-and-now but not the forever-and-ever, throwing them into iCloud backup is a waste. Apple’s servers get bloated, your app’s footprint increases, and somewhere out there, a user weeps.</p><p>So, what’s the solution? <strong>The <em>isExcludedFromBackup</em> property!</strong></p><h4>Meet isExcludedFromBackup API</h4><p>First introduced with iOS 5.1 (we’re going way back), the <em>isExcludedFromBackup</em> flag is your ticket to telling iOS: “Hey, this file? Yeah, don’t worry about it. It’s cool, but it doesn’t need to be immortalized in an iCloud backup.”</p><p>But like all good things in life, there’s a catch. This flag doesn’t always behave the way you’d expect. Sometimes, system operations (file modifications, for example) can reset this flag. That’s right. You might set it today, and after a small tweak to the file, it’s suddenly not excluded from backup anymore. Rude, right? So pay attention: every time you need to edit your file, this property can be reset, and you will reset this property.</p><h4>To Backup or Not to Backup: The File Type Dilemma</h4><p>Before diving into code, let’s quickly outline <strong>which types of files should be excluded from iCloud backups</strong>:</p><p>1. <strong>Documents</strong>: These files are precious to your users (like text files, images, or anything they’ve created). They should always be backed up to iCloud.</p><p>2. <strong>Application Support Files</strong>: These are essential for your app’s functionality, like databases or configurations, but they don’t need to be restored after a device reset. These should be <strong>excluded</strong> from iCloud backup, but <strong>they will included</strong> by iOS in the iCloud backup.</p><p>3. <strong>Temporary Files</strong>: Temporary files (stored in the tmp/ directory) are meant to be short-lived. <strong>Do not backup these files</strong>. In fact, the system may delete them at any time.</p><p>4. <strong>Caches</strong>: Files stored in the Caches/ directory help your app run faster (e.g., images or data downloaded on demand), but they don’t need to be backed up. Exclude these from iCloud backups too.</p><p>In a nutshell:</p><p>• <strong>Documents</strong> → Keep them in backups!</p><p>• <strong>Application Support</strong> → Should exclude from backups.</p><p>• <strong>Temporary</strong> → Exclude and don’t rely on them sticking around for too long.</p><p>• <strong>Caches</strong> → Exclude because they’re easily recreated.</p><h4>The Solution: Handling Backup Exclusion Like a Pro</h4><p>So, what do we do? We get clever about it. Here’s an elegant Swift extension you can use to exclude files from iCloud backup.</p><pre>import Foundation<br><br>extension URL {<br>    mutating func excludeFromBackup() throws {<br>        let fileManager = FileManager.default<br>        <br>        guard fileManager.fileExists(atPath: self.path) else {<br>            throw NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist, userInfo: [NSLocalizedDescriptionKey: &quot;File does not exist at path: \(self.path)&quot;])<br>        }<br>        <br>        var resourceValues = try self.resourceValues(forKeys: [.isExcludedFromBackupKey])<br>        <br>        if resourceValues.isExcludedFromBackup != true {<br>            resourceValues.isExcludedFromBackup = true<br>            try self.setResourceValues(resourceValues)<br>        }<br>    }<br>}</pre><p>Boom. Now you’ve got a file flagged to stay out of iCloud backup. Problem solved!</p><h4>Extension in action</h4><p>Let’s see our extension in action:</p><pre>let fileManager = FileManager()<br>let url = try fileManager.url(/service/for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true)<br>do {<br>  try url.excludeFromBackup()<br>} catch {<br>    print(&quot;Failed to exclude file from backup: \(error)&quot;)<br>}</pre><h4>Conclusion</h4><p>By excluding unnecessary files from iCloud backups, you’re doing your users (and yourself) a favor. Less bloat, faster backups, and less data being sent to Apple’s cloud. With this Swift extension, and by writing thorough tests, you’ll make sure your app handles iCloud backup exclusions like a pro.</p><p><strong>Bonus</strong>: Whether it’s <strong>Application Support</strong>, <strong>Caches</strong>, or <strong>Temporary</strong> files, remember that not everything needs to live forever in the cloud. So go forth and declutter your app’s backup! The iCloud gods and your users will thank you.</p><p>Enjoy yourself with <em>isExcludedFromBackup </em>API.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78f3c64f26da" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dependency Injection with Property Wrapper in iOS]]></title>
            <link>https://medium.com/@giulio.caggegi/dependency-injection-with-property-wrapper-in-ios-19f8c110e6b?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/19f8c110e6b</guid>
            <category><![CDATA[ios-programming]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-programming]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Thu, 22 Dec 2022 17:01:37 GMT</pubDate>
            <atom:updated>2022-12-22T17:01:37.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Inject whatever you want, where you want</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EK0x62cs2SljRJj3" /><figcaption>Photo by <a href="https://unsplash.com/@rangokonk?utm_source=medium&amp;utm_medium=referral">Raghavendra V. Konkathi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Today, we’ll try to merge two worlds in Swift: property wrappers and dependency injection. Before we start with the code, let’s quickly take a look at the concept of dependency injection.</p><h4>Dependency Injection Quickly Overview</h4><p>Dependency injection is a very simple concept. I like to summarize it with a quote from James Shore that dispels any doubts, confusion, or over-engineering about dependency injection:</p><blockquote>Dependency injection means giving an object its instance variables. Really. That’s it.</blockquote><p>Yes, that’s it. Dependency injection gives the object its dependencies and removes the responsibility for creating them from the object itself. So an object must not know how to build its dependency, but only what it does. Another object, the “<strong>Injector</strong>”, will create and inject the dependency into the object.</p><h4>Property Wrappers Quickly Overview</h4><p>The Swift property wrapper concept is very easier to understand; we can consider a Property Wrapper as an extra layer that defines how a property is stored or computed on reading. So the repetitive code used to set and get a property can be stored in a Property Wrapper. That’s it.</p><p>Now that we’ve clarified these concepts, let’s see how to implement a simple Property Wrapper for the dependency injection.</p><h4>Let’s Code</h4><p>The first thing to do is create a protocol for the injectable objects; so that every object that can be injected, will to conform this protocol:</p><pre>/// The `Injectable` protocol.<br>protocol Injectable {}</pre><p>It’s time now to create the Property Wrapper. How is useful the Property Wrapper now? And what is his value? Let’s see the code:</p><pre>@propertyWrapper<br>/// The `Inject` property wrapper.<br>struct Injected&lt;T: Injectable&gt; {<br>  // MARK: - Stored properties<br>  <br>  /// The generic `Injectable`.<br>  let wrappedValue: T<br>  <br>  // MARK: - Init<br>  <br>  /// The init of the `Inject` property wrapper.<br>  init() {<br>    wrappedValue = Resolver.shared.resolve()<br>  }<br>}</pre><p>The Property Wrapper is a generic <em>Injectable</em> object; his required property <em>wrappedValue</em> is an instance of the generic <em>Injectable.</em> The magic is in the init of the struct; the <em>wrappedValue</em> is assigned with a singleton of the <em>Resolver</em> class. Let’s analyze this class:</p><pre>/// The `Resolver` manage the storage of dependencies.<br>class Resolver {<br>  // MARK: - Stored Properties<br>  <br>  /// The shared instance of `Resolver`.<br>  static let shared = Resolver()<br>  <br>  // MARK: - Computed Properties<br>  <br>  /// The storage dictionary of the app.<br>  private var storage = [String: Injectable]()<br>  <br>  // MARK: - Init<br>  <br>  /// The init of the class.<br>  private init() {}<br>  <br>  // MARK: - Methods<br>  <br>  /// The func that stores an `Injectable` in the `storage`.<br>  /// - Parameter injectable: the `Injectable` to add to the `storage`.<br>  func add&lt;T: Injectable&gt;(_ injectable: T) {<br>    let key = String(reflecting: T.self)<br>    storage[key] = injectable<br>  }<br><br>  /// The func that returns the `Injectable`.<br>  /// - Returns: the `Injectable` to resolve.<br>  func resolve&lt;T: Injectable&gt;() -&gt; T {<br>    let key = String(reflecting: T.self)<br>    guard let injectable = storage[key] as? T else {<br>      fatalError(&quot;\(key) has not been added as an injectable object.&quot;)<br>    }<br>      <br>    return injectable<br>  }<br>}</pre><p>This class manages the dependencies, adds them, and fetches them. Notes that this is a class and not a struct, firstly because we want to change the storage when a dependency is added, and secondly is a singleton because we don’t want to have different copies of the class, but only one. The <em>add</em> and the <em>resolve</em> methods work with a generic <em>Injectable</em>.</p><p>The <em>add</em> method accepts an <em>Injectable</em> and creates a key to add it to the storage.</p><p>The <em>resolve</em> method uses the key to find the right <em>Injectable</em> in the storage.</p><p>So, how works our Property Wrapper? Simply:</p><pre>class ViewModel: {<br>  @Injected private var getDataUseCase: GetDataUseCase<br><br>...<br><br>func getData() -&gt; Data {<br>  try await getDataUseCase.execute()<br>}</pre><p>When we declare an object with <strong>Injected</strong> Property Wrapper, in his init the object will be resolved fetching it from the <strong>Resolver</strong> singleton storage.</p><h4>Dependency Manager</h4><p>We need an object responsible to add the dependencies once initialized. So we need create something like this:</p><pre>/// The struct responsible for adding the dependencies of the app&#39;s architecture.<br>struct ArchitectureDependencyManager {<br>  // MARK: - Computed Properties<br>  <br>  /// The networking manager to make API calls.<br>  private var networkingManager: NetworkingManagerProtocol {<br>    NetworkingManager()<br>  }<br><br>  // MARK: - Init<br>  <br>  /// The init of the manager.<br>  init() {<br>    addDependencies()<br>  }<br><br>  // MARK: - Private Methods<br>  <br>  /// This method adds the dependencies to the shared `Resolver` instance.<br>  private func addDependencies() {<br>    let resolver = Resolver.shared<br>    resolver.add(networkingManager)<br>  }<br>}</pre><p>Basically, in this manager object there are the instances of the <em>Injectables</em>, and in the init these instances are added to the <em>Resolver</em> storage. So, we must remember to create an instance of this object <strong>BEFORE</strong> any injectable will be used; to achieve this, we need to create an instance of the manager at the earliest point in the app lifecycle; so for an app created with UIKit in the <strong>AppDelegate</strong> class, or for an app created with SwiftUI in the <strong>App</strong> object.</p><pre>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br>  private let manager = DependencyManager()<br>...<br>}</pre><pre>@main<br>struct PokemonTestApp: App {<br>  private let manager = DependencyManager()<br>...<br>}</pre><p>We can also frame more than one dependency manager object, to manage the dependency in cascade. Let’s imagine an architecture in which a ViewModel is initialized with one or more UseCase objects. A UseCase object can be initialized with a data class, for example, a networking service class. We can use our Injected Property Wrapper to solve the dependency in all the objects! Let’s see the code:</p><pre>class HomeViewModel: BaseViewModel&lt;HomeModel&gt; {<br>  // MARK: - Stored Properties<br>  <br>  /// The use-case used to get the data list.<br>  @Injected private var getListData: GetListUseCase<br>  <br>  /// The use-case used to search for an item.<br>  @Injected private var searchItem: SearchItemUseCase<br>...<br>}</pre><p>The ViewModel has a couple of Injected UseCase objects.</p><pre>/// Get the data list.<br>  struct GetListUseCase: GetListUseCaseProtocol {<br>    @Injected private var networkingManager: NetworkingManager<br><br>    func execute() async throws -&gt; List {<br>      try await networkingManager.getList().formattedForApp()<br>    }<br>  }<br><br>/// Search an item by a query.<br>  struct SearchItemByQuery: SearchItemByQueryProtocol {<br>    @Injected private var networkingManager: NetworkingManager<br><br>    func execute(query: String) async throws -&gt; ListItem {<br>      try await networkingManager.search(by: query).formattedForApp()<br>    }<br>  }</pre><p>The UseCase objects have an Injected object, which is the networking service class.</p><p>So, the ViewModel objects have a couple of UseCase objects, that can be initialized with one or more services. We can create two different dependency manager classes to manage the dependencies in cascade and make cleaner the code. We will have the <strong>ArchitectureDependencyManager</strong> for the business dependencies like services, stores, and more; the <strong>UseCaseDepencyManager</strong> will include the UseCase objects.</p><p>Let’s see the code:</p><pre>/// The struct responsible to add the use-case objects in the Resolver.<br>struct UseCaseDepencyManager {<br>  // MARK: - Computed Properties<br>  <br>  /// The use-case used to get the data list.<br>  var getListUseCase: GetListUseCaseProtocol {<br>    GetListUseCase()<br>  }<br>  <br>  /// The use-case used to search for an item.<br>  var searchItemUseCase: SearchItemUseCaseProtocol {<br>    SearchItemUseCase()<br>  }<br><br>  // MARK: - Init<br>  <br>  /// The init of the manager.<br>  init() {<br>    addDependencies()<br>  }<br>    <br>  // MARK: - Private Methods<br>  <br>  /// This method adds the dependencies to the shared `Resolver` instance.<br>  private func addDependencies() {<br>    let resolver = Resolver.shared<br>    resolver.add(getListUseCase)<br>    resolver.add(searchItemUseCase)<br>  }<br>}</pre><pre>/// The struct responsible for adding the dependencies of the app&#39;s architecture.<br>struct ArchitectureDependencyManager {<br>  // MARK: - Computed Properties<br>  <br>  /// The networking manager to make API calls.<br>  private var networkingManager: NetworkingManagerProtocol {<br>    NetworkingManager()<br>  }<br><br>  // MARK: - Init<br>  <br>  /// The init of the manager.<br>  init() {<br>    addDependencies()<br>  }<br><br>  // MARK: - Private Methods<br>  <br>  /// This method adds the dependencies to the shared `Resolver` instance.<br>  private func addDependencies() {<br>    let resolver = Resolver.shared<br>    resolver.add(networkingManager)<br>  }<br>}</pre><p>Now we have two separate dependency managers, but we need a third manager when we will put the others in cascade. We must remember that before initializing the <strong>UseCaseDependencyManager</strong>, we must initialize the <strong>ArchitectureDependencyManager</strong> because the first needs the objects of the second to work. Let’s see the code:</p><pre>/// The class to resolve the dependencies of the app.<br>class DependencyManager {<br>  // MARK: - Stored Properties<br>  <br>  /// The responsible manager to add the dependencies of the app architecture.<br>  private var architectureDepenciesManager: ArchitectureDependencyManager<br>  <br>  /// The responsible manager to add the dependencies of the UseCases of the app.<br>  private var useCasesDepenciesManager: UseCaseDepencyManager<br>  <br>  // MARK: - Init<br>  <br>  /// The init of the manager.<br>  init() {<br>    architectureDepenciesManager = ArchitectureDependencyManager()<br>    useCasesDepenciesManager = UseCaseDepencyManager()<br>  }<br>}</pre><p>And that’s it! We have now two separate dependency managers classes that group our dependencies.</p><h4>Extra</h4><p>We’ve created a Property Wrapper to inject our dependencies into our projects, but how do we can use it on a property defined with another Property Wrapper? Imagine this situation:</p><pre>@StateObject var viewModel: HomeViewModel</pre><p>There is a way to nest more than one Property Wrapper, but this can be a bit complex and intricate. In our case, we can bypass the problem in this way:</p><pre>@StateObject var viewModel: HomeViewModel = Resolver.shared.resolve()</pre><p>Now you have a new Property Wrapper to use in your project and a new solution to manage the dependency injection on iOS. Enjoy yourself with Property Wrapper and dependency injection. See you soon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19f8c110e6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SwiftUI Gauge View]]></title>
            <link>https://medium.com/@giulio.caggegi/swiftui-gauge-view-7225d7247ca0?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7225d7247ca0</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Thu, 15 Dec 2022 14:27:10 GMT</pubDate>
            <atom:updated>2022-12-15T16:32:50.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Speed up your progress view with Gauge view</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mzt8SjZQZwacLqI_" /><figcaption>Photo by <a href="https://unsplash.com/@chrisliverani?utm_source=medium&amp;utm_medium=referral">Chris Liverani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Gauge</strong> is a new SwiftUI View introduced by Apple to help developers to shows a value within a range. If you are thinking of a semi-circular Apple widget, you are right! The semi-circular view of your widgets or your WatchOS complications can now be reproduced with a <em>Gauge View</em>. Let’s see how works.</p><h4>A Gauge View real case</h4><p>Imagine you developed a master-detail app; you have a list of objects with a stats series, and in the detail view, you want to show the stats with a progress view, maybe circular or linear(yes, it’s a Pokémon App yet). We haven’t a percent number, but a value within a range, that has a minimum(could be also a negative value or a different zero value) and a maximum value. This is the main difference between a <em>Progress View</em> and a <em>Gauge View</em>; so if we want to manage a percent value we can use a <em>Progress View</em>, while if we have a value within a range or if we want to show the value in a particular way we can use a <em>Gauge View</em>. The <em>Gauge View </em>can be customized with a preset style, a custom style, and different labels and colors.</p><h4>Gauge View in action</h4><p>Let’s see the Gauge View in action:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FqEPbbJ4g1xSCjzqn5Q-9g.png" /><figcaption>The whole code of the Gauge View</figcaption></figure><pre>Gauge(value: progress, in: mininumGaugeValue...maximumGaugeValue, label: {<br>        Text(&quot;Title&quot;)<br>      }, currentValueLabel: {<br>        Text(&quot;Current value: \(progress.formatted())&quot;)<br>      }, minimumValueLabel: {<br>        Text(mininumGaugeValue.formatted())<br>      }, maximumValueLabel: {<br>        Text(maximumGaugeValue.formatted())<br>      })</pre><p>The <em>Gauge View</em> accepts a <strong>value</strong> as a parameter, that is the value shown in the view. The <strong>bounds</strong> instead are the range with the minimum and maximum possible values(by default between 0 and 1). Moreover, you can implement these optional views:</p><ul><li><em>label</em>: The view used to describe the purpose of the gauge. Is drawn on the top of the gauge.</li><li><em>currentValueLabel</em>: The view used to show the current value. Is drawn on the bottom of the gauge.</li><li><em>minimumValueLabel</em>: The View used to show the minimum value. Is drawn at the left of the gauge.</li><li><em>maximumValueLabel</em>: The View used to show the maximum value. Is drawn at the right of the gauge.</li></ul><h4>Style</h4><p>One of the differences between a Progress View and a <em>Gauge View</em> is the styling. The <em>Gauge View</em> has a modifier, <strong><em>gaugeStyle(_ style: S)</em></strong>, that changes the view style passing an enum in this way:</p><pre>Gauge(value: progress, in: minimumGaugeValue...maximumGaugeValue) {}<br>        .gaugeStyle(.linearCapacity)</pre><p>The possible values for the styles are:</p><ul><li><strong>linearCapacity</strong>: This is the default style. It’s a simple bar that fills from left to right, exactly like a <em>Progress View</em>. The current value is on the bottom, the minimum on the left, the maximum on the right, and the title on the top.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*PV5fLqnAOUH7pTR_07Tzgg.png" /><figcaption>The Gauge View with linearCapacity style</figcaption></figure><p>. <strong>accessoryLinearCapacity</strong>: This is a compact version of <em>linearCapacity</em>. The title and the current value are positioned both towards the leading edge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*VnHFnfJ8ci4XgzZHd4BUzg.png" /><figcaption>The Gauge View with accessoryLinearCapacity style</figcaption></figure><ul><li><strong>accessoryLinear</strong>: This is a super compact version. In this style, the title label and the current value are not shown. The current value is indicated with a marker.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*ObWVcgDMSU1DaLar_nr4tQ.png" /><figcaption>The Gauge View with accessoryLinear style</figcaption></figure><ul><li><strong>accessoryCircular</strong>: This is the compact circular version. It’s a view that iOS users know right because is the view used for the weather widget in the iOS lockscreen or the WatchOS complications. There are two variants of this view; if minimum and maximum views exist, these will be shown on the left and right sides of the opening ring. Otherwise, the title view will be shown</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/379/1*52GAjOF4K49xdEyLTLWrEg.png" /><figcaption>The Gauge View with accessoryCircular style and minimum and maximum values</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*wWdK5F2_rvT6exg3w8yAdg.png" /><figcaption>The Gauge View with accessoryCircular style and title view</figcaption></figure><ul><li><strong>accessoryCircularCapacity</strong>: This is the ring version of the <em>Gauge View</em>.<em> </em>In this version, only the current value is shown</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/371/1*_1q9Vws1b6hP1HnlQ6HL1w.png" /><figcaption>The Gauge View with accessoryCircularCapacity style</figcaption></figure><p>These are the preset styles for the new<em> Gauge View</em>. Notes that all these styles are animatable; moreover, you can colorize the view with the <em>tint</em> modifier. In these examples, I used a <em>LinearGradient</em> view to colorize the views.</p><h4>Custom GaugeViewStyle</h4><p>This is the highlight of the new <em>Gauge View</em>: you can build a custom <em>GaugeStyle </em>and apply it to your view. In the example below, we can see an example implementation where our <em>GaugeStyle </em>is initialized<em> </em>with <em>@ViewBuilder</em> content. Let’s see the code:</p><pre>/// The `GaugeStyle` of the `OverallView`.<br>struct OverallGaugeStyle&lt;Content: View&gt;: GaugeStyle {<br>  // MARK: - Properties<br>  <br>  /// The `View` contained by the gauge.<br>  var content: Content<br>  <br>  /// The `LinearGradient` used to style the gauge.<br>  private var gradient = LinearGradient(<br>    colors:<br>      [<br>        Color(uiColor: AppAsset.background.color.withAlphaComponent(0.5)),<br>        Color(uiColor: AppAsset.primary.color)<br>      ],<br>    startPoint: .trailing,<br>    endPoint: .leading<br>  )<br>  <br>  // MARK: - Init<br>  <br>  /// The `init` of the `OverallGaugeStyle`.<br>  /// - Parameter content: The `View` contained by the gauge.<br>  init(@ViewBuilder content: () -&gt; Content) {<br>    self.content = content()<br>  }<br>  <br>  func makeBody(configuration: Configuration) -&gt; some View {<br>    VStack {<br>      ZStack {<br>        content<br>        <br>        Circle()<br>          .trim(from: 0, to: configuration.value * 0.75)<br>          .stroke(gradient, style: StrokeStyle(lineWidth: 20, lineCap: .round))<br>          .rotationEffect(.degrees(135))<br>          .frame(width: 250, height: 250)<br>      }<br>      <br>      configuration.currentValueLabel<br>        .fontWeight(.bold)<br>        .font(.title2)<br>        .foregroundColor(Color(uiColor: AppAsset.background.color))<br>    }<br>  }<br>}</pre><p>The custom style conforms to <strong>GaugeStyle</strong>. So, the <em>makeBody</em> method must be implemented returning a <em>View</em>; <em>makeBody </em>method accepts a <em>Configuration</em> object, which is a type alias of <em>GaugeStyleConfiguration</em>, the struct with all properties of the gauge view. So for example, if we configure the gauge view with the <em>currentValueLabel</em> view, we can use it by calling</p><pre>configuration.currentValueLabel</pre><p>In the example, an init with a <em>@ViewBuilder </em>content was added and used inside the <em>GaugeStyle</em> view. The <em>Circle</em> view is trimmed to obtain a design similar to that of the semicircle of the <em>accessoryCircular</em><strong> </strong>style.</p><p>The only thing to do now is set the custom style with the correct modifier, in this way:</p><pre>Gauge(value: progress, in: minimumGaugeValue...maximumGaugeValue) {} currentValueLabel: {<br>      VStack {<br>        Text(&quot;\(model.title): \((model.value).formatted(.number))&quot;)<br>      }<br>    }<br>    .gaugeStyle(OverallGaugeStyle {<br>      ...<br>    })</pre><p>And that&#39;s it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*ZHZGRHENsPr0EnctQKsqhA.gif" /></figure><h4>Next Steps</h4><p>Now you have a new View to design your apps when these need to show a value within a range. Design and enjoy yourself with <em>Gauge</em> View on iOS.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7225d7247ca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with iOS 16 WeatherKit]]></title>
            <link>https://medium.com/@giulio.caggegi/getting-started-with-ios-16-weatherkit-21abf6fb38ab?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/21abf6fb38ab</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[weatherkit]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Thu, 01 Dec 2022 12:34:10 GMT</pubDate>
            <atom:updated>2022-12-01T12:57:20.541Z</atom:updated>
            <content:encoded><![CDATA[<h4>Will be there sun or rain on your iPhone?</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HoKwtsExPDvlc5MSEkINDQ.png" /></figure><p>Recently Apple introduced a new framework, WeatherKit. The framework allows developers to query the Apple servers to fetch weather information. I’ll try to explain how work and what offers these new APIs. Let’s go!</p><h4>Usage Fee</h4><p>The new <em>WeatherKit</em> APIs aren’t totally free. Apple provides 500.000 API calls a month if you enrolled in the Developer Membership Program. If you need to exceed this limit you can subscribe to one of the plans provided for this service. All the subscription information and the related prices are available at this site:</p><p><a href="https://developer.apple.com/weatherkit/get-started/">Get started with WeatherKit - Apple Developer</a></p><h4>Capabilities</h4><p>In order to make the API calls you need to add the entitlement on the Apple Developer Portal and the capability in your project. The steps to make this are:</p><ul><li>Sign in to <a href="http://developer.apple.com/account">developer.apple.com/account</a>.</li><li>Search <strong>Certificates, Identifiers &amp; Profiles </strong>on the left menu.</li><li>Search <strong>Identifiers</strong> on the left menu.</li><li>Click on the “<strong>+</strong>” button to create a new identifier.</li><li>Create a new <strong>AppID </strong>for the app.</li><li>At this point, you should see the “<strong>Register an App ID</strong>” screen. Now you can select <strong>WeatherKit</strong> in the <strong>Capabilities</strong> menu.</li><li>Switch to <strong>App Services</strong> menu and select <strong>WeatherKit</strong>.</li><li>NOTE: it’s important now, according to Apple documentation, wait for at least 30 minutes for the service to register your app.</li><li>Open your Xcode project, and add the capability for <strong>WeatherKit</strong>.</li></ul><p>Finally, you are able to call the <strong>WeatherKit</strong> API.</p><h4>Attribution</h4><p>Before all, notes that if you want to use the WeatherKit API in an AppStore app, you must show the attribution. Apple provides an object for this, which is <em>WeatherAttribution</em>. This object contains two properties, an image, and a link. The image is provided through an URL and is available in various variants; so we will have the <strong>combinedMarkDarkURL</strong> and the <strong>combinedMarkLightURL</strong>. The link contains a link to the legal attribution page that contains copyright information about the weather data sources.</p><p>The attribution object can be fetched in this way:</p><pre>func getAttribution() async throws -&gt; WeatherAttribution {<br>  let attribution = try await WeatherService.shared.attribution<br>}</pre><p>As you can see, the attribution method throws the WeatherAttribution object in an async way.</p><h4>Fetch the weather information</h4><p>The weather data provider it’s a simple class that encapsulates all the methods to fetch the information, that is <strong>WeatherService</strong>. You can instantiate a new <strong>WeatherService </strong>class, or use the single shared singleton provided by Apple:</p><pre>/// The Apple weather service.<br>private let weatherService: WeatherService = {<br>  WeatherService()<br>}()<br><br>/// The Apple weather sahred service.<br>private let sharedWeatherService = WeatherService.shared</pre><p>This class has a single method that returns the weather forecast for the requested location:</p><pre>weather&lt;T&gt;(for location: CLLocation, including dataSet: WeatherQuery&lt;T&gt;) async throws -&gt; T</pre><p>This is a dynamic API that contains more than a query, and returns the forecast as a tuple. Let’s see some examples:</p><pre>let location = try await locationWorker.getCurrentLocation()<br>let weather = try await service.weather(for: location, including: .current)</pre><pre>let location = try await locationWorker.getCurrentLocation()<br>let weather = try await service.weather(for: location, including: .current, .alerts, .daily)</pre><p>In the first example, we requested(in an async way) the current user location and the current forecast weather passing the .current query.</p><p>In the second example, we requested the current forecast weather, the alerts, and the daily forecast. In this case, the result will be returned in a tuple, so we will access the current forecast with weather.0 , the alerts with weather.1, and the daily forecasts with weather.2 . Apple provides a big set of weather queries:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/384/1*-YSpaX--JSHf5p_qg0hdxA.png" /><figcaption>The weather queries provided by Apple</figcaption></figure><p>Notes that iOS provides a method to format and localize the data in your local region. To do this, you can call the formatted API:</p><pre>weather.temperature.formatted(.measurement(width: .wide, usage: .weather))</pre><h4>CurrentWeather and DailyForecast</h4><p>The CurrentWeather object includes a lot of information to show, such as:</p><ul><li><em>temperature</em>: the current temperature of the air.</li><li><em>condition</em>: an enumeration that represents the condition at the time.</li><li><em>apparentTemperature</em>: the feel-like temperature.</li><li><em>symbolName</em>: a useful string indicating the current weather system symbol to use to represent the weather condition.</li><li><em>cloudCover</em>: the percentage(between 0 and 1) of the covered sky.</li><li><em>dewPoint</em>: the temperature at which relative humidity is 100%.</li><li><em>humidity</em>: the humidity of the air.</li><li><em>isDaylight</em>: a boolean indicating if there is daylight.</li><li><em>wind</em>: an object with wind, direction, and speed.</li><li><em>visibility</em>: the distance at which terrain is visible.</li></ul><p>and moreover.</p><p>Also the daily weather forecast contains a lot of useful information. Some examples are:</p><ul><li><em>moon</em>: the information about the moon.</li><li><em>sun</em>: the information about the sunrise and the sunset.</li><li><em>precipitationChance</em>: the chance of rain.</li><li><em>highTemperature</em>: the maximum temperature of the day.</li><li><em>lowTemperature</em>: the lowest temperature of the day.</li></ul><p>and moreover.</p><h4>REST API</h4><p>Over the iOS APIs, Apple released in beta also the WeatherKit REST API. So we can use the same weather information in a web app, on Android, or another platform. You can find all the information about the REST API here:</p><p><a href="https://developer.apple.com/documentation/weatherkitrestapi">Apple Developer Documentation</a></p><h4>Next Steps</h4><p>Now you know the basics of the new WeatherKit framework; you can explore it, test it and use it in a lot of ways. Enjoy yourself with the new WeatherKit Framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*GufCKz0NZ7mD8fwvzeJKRA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21abf6fb38ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using App Intents with iOS 16]]></title>
            <link>https://medium.com/@giulio.caggegi/use-app-intents-with-ios-16-90a341ccbc94?source=rss-c1fc89daa3f7------2</link>
            <guid isPermaLink="false">https://medium.com/p/90a341ccbc94</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[framework]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Giulio Caggegi]]></dc:creator>
            <pubDate>Fri, 25 Nov 2022 18:00:50 GMT</pubDate>
            <atom:updated>2022-12-01T12:55:09.616Z</atom:updated>
            <content:encoded><![CDATA[<h4>Use your iPhone with your voice: the dream of every iOS user</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*bs9K9bK_AsllfP3RTJAhGQ.png" /></figure><p>Recently Apple introduced a new framework, App Intents. The goal of this framework is simplify the code to interact with Siri and improve the user experience with your own iPhone. In this post I’ll explain how to approach this framework, what are the main heroes and how they interact among them.</p><h3>Intents and App Shortcut</h3><p>Firstly, we’ll analyze the main actors of these framework, Intent and Shortcut. An Intent is simply an action that iOS can execute. In the Apple documentation the intent description is:</p><blockquote>An app intent includes the code you need to perform an action, and describes the data you require from the system</blockquote><p>In the Apple way, generally an intent is a piece of code that Siri can execute. We can combine more intents like a puzzle to create more complex activities or a sensible sequence: this is the App Shortcut job! The App Shortcut is famous for iOS users; through “Shortcut” app, users can create a sequence of executable actions and associate a phrase to start them with Siri. The new App Intents framework gives the possibility to developers to create and build an App Shortcut without no longer need the setup of the user. The shortcut can be used in Shortcut app, but can’t be edited by the user.</p><p>The framework gives the possibility to set also a series of sentences that the user can pronounces to activate the Shortcut with Siri.</p><h3>App Entity</h3><p>The <em>AppEntity</em> is the domain model of our shortcuts. Let’s see the code:</p><pre>/// This is the model used with `AppIntents` framework.<br>@available(iOS 16.0, *)<br>struct PokemonAppEntity: AppEntity, Identifiable {<br>  <br>  /// The `TypeDisplayRepresentation` of the entity.<br>  static var typeDisplayRepresentation = TypeDisplayRepresentation(name: &quot;Pokemon&quot;)<br>  <br>  /// The needed `defaultQuery` in order to conform `PokemonAppEntity` to `AppEntity`.<br>  static var defaultQuery: PKMNIntentsQuery = PKMNIntentsQuery()<br>  <br>  /// The unique `String` used to identify the entity.<br>  var id: String<br>  <br>  /// The `@Property` for the name.<br>  @Property(title: &quot;Name&quot;)<br>  var name: String<br>  <br>  /// The `DisplayRepresentation` type planned by the `AppEntity`.<br>  /// A type that describes the user interface presentation of a custom type.<br>  var displayRepresentation: DisplayRepresentation {<br>    return DisplayRepresentation(<br>      title: &quot;\(name)&quot;,<br>      subtitle: nil,<br>      image: .init(data: AppAsset.pokeball.image.pngData())<br>    )<br>  }<br>  <br>  // MARK: - Init<br>  <br>  init(id: String, name: String) {<br>    self.id = id<br>    self.name = name<br>  }<br>}<br><br>// MARK: - Extensions<br><br>@available(iOS 16.0, *)<br>extension PokemonAppEntity: Equatable {<br>  static func == (lhs: PokemonAppEntity, rhs: PokemonAppEntity) -&gt; Bool {<br>    return lhs.id == rhs.id<br>  }<br>}<br><br>@available(iOS 16.0, *)<br>extension PokemonAppEntity: Hashable {<br>  func hash(into hasher: inout Hasher) {<br>    hasher.combine(id)<br>  }<br>}</pre><p>The <em>PokemonAppEntity </em>struct needs to conform the <em>AppEntity </em>and <em>Identifiable</em> protocols. The <em>AppEntity</em> expects:</p><ul><li>A static <em>TypeDisplayRepresentation</em>, that is a title used in different places to describe the entity.</li><li>A <em>DisplayRepresentation</em>, that is a struct with a title, an optional subtitle and an image, used in the Shortcut App to show an instance of the entity. Notes that the image must be a static image, never dynamic.</li><li>A static <em>defaultQuery</em>, an interface for locating entities using their identifiers.</li><li>We added also a @<em>Property</em> name String, which exposes to the system the String associated property.</li></ul><p>In the extension we made the entity conform to Hashable and Equatable protocols.</p><h3>EntityQuery</h3><p>As seen, the <em>AppEntity</em> protocol expects a <em>defaultQuery</em>, in order to allow Siri and Shortcut app to fetch the <em>AppEntity</em>. So we must implement a class conform to <em>EntityQuery</em> protocol. In this way, Siri and App Shortcuts can fetch exactly the entity the user is referring to.</p><p>For example, a user may have chosen a Pokemon from a list when tapping on a parameter that accepts Pokemon. The ID of that Pokemon is now hardcoded into the Shortcut.</p><pre>import AppIntents<br><br>/// The `EntityPropertyQuery` of the `PokemonAppEntity`.<br>@available(iOS 16.0, *)<br>struct PKMNIntentsQuery: EntityQuery {<br>  // MARK: - Entities Methods<br>  <br>  /// Find an entity by his ID.<br>  /// For example a user may have chosen a Pokemon from a list when tapping on a parameter that accepts Pokemon. The ID of that Pokemon is now hardcoded into the `Shortcut`.<br>  /// - Parameter identifiers: The list of IDs for the Pokemons that the user selected.<br>  /// - Returns: The list of `[PokemonAppEntity]` found.<br>  func entities(for identifiers: [String]) async throws -&gt; [PokemonAppEntity] {<br>    let pokemons = try await IntentsLogic.FetchData.Pokemons.execute()<br>    return pokemons.filter { identifiers.contains($0.id) }<br>  }<br>  <br>  /// Returns all Pokemon. This is what populates the list when you tap on a parameter that accepts a Pokemon.<br>  func suggestedEntities() async throws -&gt; [PokemonAppEntity] {<br>    try await IntentsLogic.FetchData.Pokemons.execute()<br>  }<br>}</pre><p>The protocol expects also to implement the <em>suggestedEntities</em>, which returns the initial results shown when a list of options backed by this query is presented. All the entities&#39; methods are asynchronous.</p><p>But…we have a @<em>Property </em>var in our AppEntity. Can we use this property to query an <em>AppEntity</em>? The answer is “yes, we can”! We must conform our <em>PKMNIntentsQuery</em> to <em>EntityPropertyQuery</em>. To do this, we must add some properties to our struct:</p><ul><li>A list of EntityQueryProperties</li><li>A list of SortingOptions</li><li>A new entities method</li></ul><pre>/// The `EntityPropertyQuery` of the `PokemonAppEntity`.<br>@available(iOS 16.0, *)<br>struct PKMNIntentsQuery: EntityPropertyQuery {<br>  <br>  // MARK: - Computed Properties<br>  <br>  /// A type that provides the properties to include in a property-matched query.<br>  static var properties = EntityQueryProperties&lt;PokemonAppEntity, String&gt; {<br>    Property(\.$name) {<br>      EqualToComparator { $0 }<br>      ContainsComparator { $0 }<br>    }<br>  }<br>  <br>  /// The sorting options provided by the `EntityPropertyQuery` protocol.<br>  static var sortingOptions = SortingOptions {<br>    SortableBy(\.$name)<br>  }<br>  <br>  // MARK: - Entities Methods<br>  <br>  /// Find an entity by his ID.<br>  /// For example a user may have chosen a Pokemon from a list when tapping on a parameter that accepts Pokemon. The ID of that Pokemon is now hardcoded into the `Shortcut`.<br>  /// - Parameter identifiers: The list of IDs for the Pokemons that the user selected.<br>  /// - Returns: The list of `[PokemonAppEntity]` found.<br>  func entities(for identifiers: [String]) async throws -&gt; [PokemonAppEntity] {<br>    let pokemons = try await IntentsLogic.FetchData.Pokemons.execute()<br>    return pokemons.filter { identifiers.contains($0.id) }<br>  }<br>  <br>  func entities(matching comparators: [String], mode: ComparatorMode, sortedBy: [Sort&lt;PokemonAppEntity&gt;], limit: Int?) async throws -&gt; [PokemonAppEntity] {<br>    guard !comparators.isEmpty, let name = comparators.first else {<br>      return try await IntentsLogic.FetchData.Pokemons.execute()<br>    }<br>    return try await IntentsLogic.FetchData.PokemonByQuery.execute(query: name)<br>  }<br>  <br>  /// Returns all Pokemon. This is what populates the list when you tap on a parameter that accepts a Pokemon.<br>  func suggestedEntities() async throws -&gt; [PokemonAppEntity] {<br>    try await IntentsLogic.FetchData.Pokemons.execute()<br>  }<br>}</pre><p>The <em>EntityQueryProperties</em> has a list of <em>EntityQueryComparator</em> that specifies a particular query comparison that can be made against a <em>EntityQueryProperty</em>. The <em>EntityQueryComparator</em>, like <em>EqualToComparator</em> or <em>ContainsComparator</em> are called at runtime with “value” being the user-supplied value. In our case the comparator is a simple <em>String</em>, but can be a <em>NSPredicate</em> or a <em>URLQueryItem </em>or whatever.</p><p>The comparators are the input for the new <em>entities</em> method, and can be used to filter the <em>AppEntity</em>.</p><p>If all is right, you can find in the Shortcut app a new shortcut action like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*dq3DHMnsm3fou0vt4WEgtQ.png" /></figure><h3>App Intent</h3><p>Now we have our <em>AppEntity</em> and our <em>EntityQuery</em>; it’s time to see the <em>App Intent.</em> Let’s see the code:</p><pre>@available(iOS 16, *)<br>/// This is the real implementation of `AppIntent`. Is the action to show the information about a `PokemonAppEntity`.<br>struct CatchPokemon: AppIntent {<br>  /// The title of the action in the `Shortcut` app.<br>  static var title: LocalizedStringResource = PKMNString.AppIntents.title<br>  <br>  /// The description of the action.<br>  static var description: IntentDescription = IntentDescription(stringLiteral: String(localized: PKMNString.AppIntents.description))<br>  <br>  /// Authentication policies to apply when running an app intent.<br>  static var authenticationPolicy = IntentAuthenticationPolicy.alwaysAllowed<br>  <br>  /// Wheter or not the app should be open or not.<br>  static var openAppWhenRun = false<br>  <br>  /// The dynamic lookup parameter.<br>  @Parameter(title: &quot;Pokemon&quot;)<br>  var pokemon: PokemonAppEntity?<br>  <br>  @MainActor<br>  func perform() async throws -&gt; some ReturnsValue&lt;PokemonAppEntity&gt; {<br>    let pokemonToCatch: PokemonAppEntity<br>    if let pokemon = pokemon {<br>      pokemonToCatch = pokemon<br>    } else {<br>      pokemonToCatch = try await $pokemon.requestDisambiguation(among: try await IntentsLogic.FetchData.Pokemons.execute(), dialog: IntentDialog(stringLiteral: String(localized: PKMNString.AppIntents.dialog)))<br>    }<br>    return .result(value: pokemonToCatch, view: PokemonInformation(pokemon: pokemonToCatch))<br>  }<br>}</pre><p>This simple <em>AppIntent</em> shows in a View the information of the selected Pokemon.</p><p>Our struct must be conforming the <em>AppIntent</em> protocol, so we need to implement some static properties:</p><ul><li>The <em>LocalizedStringResource</em> title, that is the title of the action.</li><li>The <em>IntentDescription</em> description, that is the description of the action.</li></ul><p>Optionally, we can specify other static properties, such as the <em>IntentAuthenticationPolicy </em>or the boolean <em>openAppWhenRun</em>.</p><p>The <em>IntentAuthenticationPolicy </em>describes the authentication policy to use when an <em>AppIntent</em> running. So for example we can set the policy to <em>alwaysAllowed</em> if the <em>AppIntent</em> can be run even on a locked device; the others possible values are</p><ul><li><em>requiresAuthentication</em> when the <em>AppIntent</em> requires the user to authenticate in the local device or in a paired device such as an Apple Watch.</li><li><em>requiresLocalDeviceAuthentication</em> when the <em>AppIntent</em> requires the user to authenticate only in the local device.</li></ul><p>The boolean <em>openAppWhenRun </em>instead describes when the main app should be open or not.</p><p>To determine which Pokemon to show, we’ve added a <em>pokemon</em> property to our struct. This property is configured with the @<em>Parameter</em> property wrapper.</p><p>The next step is to implement the <em>perform</em> method. When our App Intent is executed, we may already know what Pokemon the user intends to see, or we may not have that information yet(for example if the user use the Intent in the <em>Shortcut</em> app), so we need to support both scenarios.</p><p>The App Intents framework provides <em>Disambiguation</em> to ask users follow-up questions. A disambiguation is triggered by calling <em>requestDisambiguation(among:dialog:)</em> on our Pokemon property wrapper, known as $pokemon.</p><p>The <em>perform</em> method returns with an <em>IntentResult</em>. In the example we use the method to return a value, that the user can use in a Shortcut sequence; the same result is used to present a simple SwiftUI View with the related value’s information. As you can see, we have multiple solutions and possibilities:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*BIHkYj66OMghViPDGPOcpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*G1MZdHdbqVsBR1YQFtvYzg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*R29c0Rumbi4oqw5uXamzdg.png" /></figure><h3>App Shortcut</h3><p>The last step is to create an <em>AppShortcut</em> in order to execute automatically the <em>AppIntent</em>. Let’s see the code:</p><pre>@available(iOS 16.0, *)<br>/// The `AppShortcutsProvider`.<br>struct PokemonShortcutsProvider: AppShortcutsProvider {<br>  @AppShortcutsBuilder<br>  static var appShortcuts: [AppShortcut] {<br>    AppShortcut(<br>      intent: OpenPokemon(),<br>      phrases: [&quot;Catch a Pokemon in \(.applicationName)&quot;]<br>    )<br>  }<br>}</pre><p>The array of phrases contains the possible sentences(also localized phrases, as we will see after), that the users can pronounce to execute the intent. Notes that all the phrases must contain the <em>applicationName</em> app token.</p><p>Now, it’s possible to execute the intent pronouncing a phrase, or find it in the Shortcut app or in the Siri suggestion flow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*7pkB51lTxMI07fFmM6d26A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*w3qDQQQkSAz0gikenKsxTw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*PZz1HdftDwQVDYT8Inf5aA.png" /></figure><h3>Localization</h3><p>A special chapter is dedicated to the localization of the <em>AppShortcut</em>. Notes that all the parameters and the presented intent dialogs must be localized with the new <em>LocalizedStringResource</em> struct. For example, we can ask Siri to read a phrase, presenting an <em>IntentDialog</em>. If we want to localize the string, we can do it in this way:</p><pre>IntentDialog(stringLiteral: String(localized: LocalizedStringResource(...)))</pre><p>The <em>init</em> of the <em>LocalizedStringResource </em>allows us to specify the table and the key for the localization.</p><p>We can localize also the phrases of the array of the <em>AppShortcut</em> . To make this, we must create a new strings file exactly with the <em>AppShortcuts.strings </em>name;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*s3fXwLweMBiLp_gnc-YivA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*IURuHprD4MlhH4TfBMMkLg.png" /></figure><p>Notes that all the strings used for the <em>AppShortcuts</em> must contain the application name surrounded in this way:</p><pre>${applicationName}</pre><p>In our <em>AppShortcutsProvider</em> we will able to pass directly the key of the localized string in this way:</p><pre>@available(iOS 16.0, *)<br>/// The `AppShortcutsProvider`.<br>struct PokemonShortcutsProvider: AppShortcutsProvider {<br>  @AppShortcutsBuilder<br>  static var appShortcuts: [AppShortcut] {<br>    AppShortcut(<br>      intent: OpenPokemon(),<br>      phrases: [&quot;shortcut.show.pokemons&quot;]<br>    )<br>  }<br>}</pre><h3>Next Step</h3><p>Now you know the step-by-step instructions to implement <em>AppShortcut</em> and <em>AppIntent</em>. You can explore the configurations, parameters and possibilities that this framework offers. Enjoy yourself with <em>AppIntents</em> framework!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90a341ccbc94" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>