<?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 Drew Althage on Medium]]></title>
        <description><![CDATA[Stories by Drew Althage on Medium]]></description>
        <link>https://medium.com/@drewalth?source=rss-f64f438fae9a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*_V5Fgc3UqkNpCertrWonFg.jpeg</url>
            <title>Stories by Drew Althage on Medium</title>
            <link>https://medium.com/@drewalth?source=rss-f64f438fae9a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 12:22:53 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@drewalth/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[PocketBase and Swift]]></title>
            <link>https://medium.com/@drewalth/pocketbase-and-swift-e9ee28421498?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9ee28421498</guid>
            <category><![CDATA[pocketbase]]></category>
            <category><![CDATA[prototyping]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 17:03:25 GMT</pubDate>
            <atom:updated>2025-10-07T17:03:25.052Z</atom:updated>
            <content:encoded><![CDATA[<p>The framework and SDK for rapid prototyping iOS apps</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JZSWlZnZ3xCqeRcXrBY1hw.png" /></figure><p>There are many *base frameworks out there; AppBase, SupaBase, FireBase, etc, and they all do pretty much the same thing with varying degrees of complexity and features.</p><p>Amongst this crowded playing field, <a href="https://pocketbase.io/">PocketBase</a> stands out as a <em>free, open-source, easy-to-use</em>, and batteries-included backend framework.</p><p>PocketBase is a great choice for rapid prototyping and small to medium-sized projects. A few features in particular make it a standout:</p><ul><li>Easy to use. Drop a few lines into a main.go file and you’re off to the races.</li><li>All the tedious details are handled for you. Authentication, data modeling, HTTP endpoints, etc.</li><li>Runs well in resource-constrained environments, such as your old, dusty Raspberry Pi.</li><li>Excellent feature-rich client-side SDKs for JavaScript and Dart.</li></ul><p>All of this is great. However, as an iOS developer, I’ve been wanting a Swift SDK for PocketBase for some time now. Something that would allow me to quickly hack on my next billion-dollar app idea without having to spend hours setting up a backend.</p><p><strong><em>Warning: shameless plug ahead.</em></strong></p><p>Enter the PocketBase Swift SDK; <a href="https://github.com/drewalth/pocketbase-swift-sdk.">https://github.com/drewalth/pocketbase-swift-sdk.</a></p><p>The SDK still lacks 100% feature parity with the JavaScript and Dart SDKs, but it’s already a great way to get started with PocketBase and Swift.</p><p>What it does support:</p><ul><li>Collection CRUD operations with type-safe models.</li><li>Email/Password Authentication (sign up, sign in, sign out).</li><li>Real-time subscriptions to collections and records.</li><li>Swift 6</li></ul><h4>Example</h4><p>Here is a quick example of how to use the SDK to load a collection into a SwiftUI view.</p><p>First, we need to create a model for our posts collection that we want to load into the app.</p><pre>import PocketBase<br><br>struct Post: PBBaseRecord {<br>    let id: String<br>    let title: String<br>    let created: String<br>    let updated: String<br>}</pre><p>Next, we create the PocketBase client and add it to the SwiftUI environment.</p><pre>import PocketBase<br>import SwiftUI<br><br>struct PB: EnvironmentKey {<br>  static let defaultValue = PocketBase(baseURL: &quot;http://127.0.0.1:8090&quot;)<br>}<br><br>extension EnvironmentValues {<br>  var pocketBase: PocketBase {<br>    get {<br>      self[PB.self]<br>    } set {<br>      self[PB.self] = newValue<br>    }<br>  }<br>}</pre><p>Now we create a view, a collection, and a task to load the posts into the view.</p><pre>struct PostList: View {<br>    @Environment(\.pocketBase) var pocketBase<br>    @State var posts: [Post] = []<br><br>    var body: some View {<br>        List(posts, id: \.id) { post in<br>            Text(post.title)<br>        }.task {<br>            do {<br>                let postCollection: Collection&lt;Post&gt; = try await pocketBase.collection(&quot;posts&quot;)<br>                let postsResult = try await postCollection.getList()<br>                self.posts = postsResult.items<br>            } catch {<br>                print(error)<br>            }<br>        }<br>    }<br>}</pre><p>And now we can use the collection in our view!</p><p>For a more complete example, check out the <a href="https://github.com/drewalth/pocketbase-swift-sdk/tree/main/example">example project</a>.</p><h4>Contributing + Feedback</h4><p>Contributions and feedback are welcome! Please feel free to submit an issue or a pull request.</p><h4>Acknowledgements</h4><p>Thanks to the PocketBase team for creating such a great backend framework!</p><p>Learn more about the framework at <a href="https://pocketbase.io/">https://pocketbase.io/</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9ee28421498" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Restricting UI Component APIs — A Strategy for Efficient Rebranding]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@drewalth/restricting-ui-component-apis-a-strategy-for-efficient-rebranding-39d25e764856?source=rss-f64f438fae9a------2"><img src="https://cdn-images-1.medium.com/max/1792/1*_9NGjdWOWNpykFOWp6LRYQ.png" width="1792"></a></p><p class="medium-feed-snippet">How Locking Down UI Overrides Saves Your Future Self (and Brand) a Heap of Trouble</p><p class="medium-feed-link"><a href="https://medium.com/@drewalth/restricting-ui-component-apis-a-strategy-for-efficient-rebranding-39d25e764856?source=rss-f64f438fae9a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@drewalth/restricting-ui-component-apis-a-strategy-for-efficient-rebranding-39d25e764856?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/39d25e764856</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[branding]]></category>
            <category><![CDATA[design-thinking]]></category>
            <category><![CDATA[design]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Wed, 03 Apr 2024 06:22:49 GMT</pubDate>
            <atom:updated>2024-04-10T05:43:12.788Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Mostly Stressless Stress Testing]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@drewalth/stress-testing-terminal-commands-5962c5ed2104?source=rss-f64f438fae9a------2"><img src="https://cdn-images-1.medium.com/max/1024/1*KCt6GvykVirivE1gISJf5A.jpeg" width="1024"></a></p><p class="medium-feed-snippet">Using Go to Aid in JavaScript Development: a Profound Success Story</p><p class="medium-feed-link"><a href="https://medium.com/@drewalth/stress-testing-terminal-commands-5962c5ed2104?source=rss-f64f438fae9a------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@drewalth/stress-testing-terminal-commands-5962c5ed2104?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5962c5ed2104</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Wed, 28 Feb 2024 07:02:02 GMT</pubDate>
            <atom:updated>2024-02-28T18:58:54.376Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Deploy CoreML Models on the Server with Vapor]]></title>
            <link>https://medium.com/better-programming/deploy-coreml-models-on-the-server-with-vapor-48809a853fae?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/48809a853fae</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[apple]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Tue, 07 Nov 2023 20:06:54 GMT</pubDate>
            <atom:updated>2023-11-10T17:30:15.819Z</atom:updated>
            <content:encoded><![CDATA[<p>Get the benefits of Apple’s ML tools server-side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XMjKfWYZYPikQ0pJ391YaA.png" /><figcaption>SwiftUI client showing image classification results</figcaption></figure><p>Recently, at <a href="https://www.sovrn.com/">Sovrn</a>, we had an AI Hackathon where we were encouraged to experiment with anything related to machine learning. The Hackathon yielded some fantastic projects from across the company. Everything from SQL query generators to chatbots that can answer questions about our products and other incredible work. I thought this would be a great opportunity to learn more about Apple’s ML tools and maybe even build something with real business value.</p><p>A few of my colleagues and I teamed up to play with CreateML and CoreML to see if we could integrate some ML functionality into our iOS app. We got a model trained and integrated into our app in several hours, which was pretty amazing. But we quickly realized that we had a few problems to solve before we could actually ship this thing.</p><ul><li>The model was hefty. It was about 50MB. That’s a lot of space to take up in our app bundle.</li><li>We wanted to update the model without releasing a new app version.</li><li>We wanted to use the model in the web browser as well.</li></ul><p>We didn’t have time to solve all of these problems. But the other day I was exploring the <a href="https://vapor.codes/">Vapor</a> web framework and the thought hit me, “Why not deploy CoreML models on the server?”</p><p>Apple provides a few pre-trained models, so today we’ll deploy an image classification model on the server behind a REST API with Vapor and create a SwiftUI client to consume it.</p><h3>Foreword</h3><p>This prototype is just that, a prototype. It’s not meant to be a production-ready solution. It’s meant to be a proof of concept. There will be warnings in the console, and the code won’t be very clean, but it will work and hopefully get your wheels turning.</p><p>If you want to skip all this, or if you do want to follow along, you can find the source code for this project on <a href="https://github.com/drewalth/coreml-web-api">GitHub</a>.</p><p>Okay, disclaimers over. Let’s get started!</p><h3>Requirements</h3><ul><li>Xcode 15</li><li>macOS 14</li><li>Homebrew</li><li>Apple Developer Account + Physical Device for testing</li></ul><h3>Getting Started</h3><p>First start by creating a new directory that will house our Xcode workspace. We’ll call it coreml-web-api .</p><pre>cd ~/Desktop &amp;&amp; mkdir coreml-web-api &amp;&amp; cd coreml-web-api</pre><p>Now let&#39;s install Vapor and bootstrap a brand new server. See <a href="https://docs.vapor.codes/">the docs</a> for more details.</p><pre>brew install vapor<br>vapor new server -n<br>open Package.swift</pre><p>We want our users to be able to upload images for classification so add a new route called classify that supports this. In server/Sources/App/routes.swift , clear out all that generated boilerplate, and add in the following:</p><pre>import CoreImage<br>import Vapor<br><br>func routes(_ app: Application) throws {<br>    app.post(&quot;classify&quot;) { req -&gt; [ClassifierResult] in<br>        let classificationReq = try req.content.decode(ClassificationRequest.self)<br>        let imageBuffer = classificationReq.file.data<br>        guard let fileData = imageBuffer.getData(at: imageBuffer.readerIndex, length: imageBuffer.readableBytes),<br>              let ciImage = CIImage(data: fileData)<br>        else {<br>            throw Errors.badImageData<br>        }<br><br>        let classifier = Classifier() // we&#39;ll add this in a sec<br><br>        return try classifier.classify(image: ciImage)<br>    }<br>}<br><br>enum Errors: Error {<br>    case badImageData // or whatever<br>}<br><br>struct ClassificationRequest: Content {<br>    var file: File<br>}</pre><p>Also, bump up the max file size allowed for uploads in configure.swift :</p><pre>import Vapor<br><br>// configures your application<br>public func configure(_ app: Application) async throws {<br>    app.routes.defaultMaxBodySize = &quot;10mb&quot;<br><br>    // register routes<br>    try routes(app)<br>}</pre><p>Alright, now let&#39;s write up a Classifier API. First, head over to <a href="https://developer.apple.com/machine-learning/models/">Apple’s ML page</a> to download a pre-trained model of your choosing. In this demo, I’m using the Resnet50 model. We’ll add this to the package in just a moment.</p><p>Add a new file called Classifier and drop in the following:</p><pre>import CoreImage<br>import Vapor<br>import Vision<br><br>struct Classifier {<br>    func classify(image: CIImage) throws -&gt; [ClassifierResult] {<br>        let url = Bundle.module.url(/service/forresource: &quot;Resnet50&quot;, withExtension: &quot;mlmodelc&quot;)!<br>        guard let model = try? VNCoreMLModel(for: Resnet50(contentsOf: url, configuration: MLModelConfiguration()).model) else {<br>            throw Errors.unableToLoadMLModel<br>        }<br><br>        let request = VNCoreMLRequest(model: model)<br><br>        let handler = VNImageRequestHandler(ciImage: image)<br><br>        try? handler.perform([request])<br><br>        guard let results = request.results as? [VNClassificationObservation] else {<br>            throw Errors.noResults<br>        }<br><br>        return results.map { ClassifierResult(label: $0.identifier, confidence: $0.confidence) }<br>    }<br><br>    enum Errors: Error {<br>        case unableToLoadMLModel<br>        case noResults<br>    }<br>}<br><br>struct ClassifierResult: Encodable, Content {<br>    var label: String<br>    var confidence: Float<br>}</pre><p>Let’s break this down.</p><p>First, we load the model. Adding a CoreML model to a package is not super straightforward. We need to compile the .mlmodelourselves and add some files to Sources/. We’ll go over that in a few but this wonkiness explains why loading the model might look slightly different from adding one to a standard Xcode project.</p><p>Once the model is loaded, we prepare the request and the request handler; then we do the classification. To send the results as JSON to the client, we need to remap the results to a structure that conforms to Encodable and Content .</p><h4>Adding the Model to the Package</h4><p>This part definitely took me the longest to figure out. Unfortunately, this step is pretty manual; we can’t just drag and drop the model into the project. So, at the root of the server package, add a new folder called MLModelSource and add the Resnet50.mlmodel file here. Create another folder called Resourcesat server/Sources/App/Resources/ .</p><p>Now, we need to compile the model, add the Swift class to sources, and include the .mlmodelc in the package bundle. The compilation steps are repetitive so we’ll place them in a Makefile target. In the project root, create a Makefile:</p><pre># ~/Desktop/coreml-web-api/<br>touch Makefile</pre><p>And add a compile_ml_modeltarget:</p><pre>compile_ml_model:<br>   cd server/MLModelSource &amp;&amp; \<br>   xcrun coremlcompiler compile Resnet50.mlmodel ../Sources/App/Resources &amp;&amp; \<br>   xcrun coremlcompiler generate Resnet50.mlmodel ../Sources/App/Resources --language Swift</pre><p>Next, add this to the executable target inPackage.swift file:</p><pre>resources: [<br>    .copy(&quot;Resources/Resnet50.mlmodelc&quot;),<br>]</pre><p>The target should look like this:</p><pre>.executableTarget(<br>    name: &quot;App&quot;,<br>    dependencies: [<br>        .product(name: &quot;Vapor&quot;, package: &quot;vapor&quot;),<br>    ],<br>    resources: [<br>        .copy(&quot;Resources/Resnet50.mlmodelc&quot;),<br>    ]<br>),</pre><p>Okay, now from the project root, run the compile_ml_model target:</p><pre>make compile_ml_model</pre><p>Awesome!!! Now, we have an amazing server that supports classifying uploaded images using the Resnet50 model. Before we move on to the creating the client, we need to adjust the App scheme to make the server available to a physical device on your network.</p><p>Open up the scheme editor, and add serve --hostname 0.0.0.0 to the run arguments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9D7VFpFoUNxS6uZPqCVESw.png" /></figure><p>Sweet. Now, we’ll create a client to do the uploading.</p><h3>iOS Client</h3><p>OK, in Xcode go to File -&gt; New -&gt; Project and add an iOS app to the workspace. We only need SwiftUI, no tests or SwiftData. I’m giving mine a really clever name of CoreMLWebClient … poetic.</p><p>Great. Now, let&#39;s do a little config work. Since we’re going to be using the camera, we need to update the Info.plist with the Privacy — Camera Usage Description key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PVfyDXPGfo9-oeQIercJjg.png" /></figure><p>Nice! In our client, we want to give users the option of using the camera or selecting from the photo library. Create a new file called ImagePicker.swift and paste in the following:</p><pre>import SwiftUI<br><br>struct ImagePicker: UIViewControllerRepresentable {<br>    @Binding var sourceType: UIImagePickerController.SourceType<br>    @Environment(\.presentationMode) private var presentationMode<br>    var completion: (UIImage) -&gt; Void<br><br>    func makeUIViewController(context: Context) -&gt; some UIViewController {<br>        let picker = UIImagePickerController()<br>        picker.sourceType = sourceType<br>        picker.delegate = context.coordinator<br>        return picker<br>    }<br><br>    func updateUIViewController(_: UIViewControllerType, context _: Context) {}<br><br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(self)<br>    }<br><br>    class Coordinator: NSObject, UINavigationControllerDelegate, UIImagePickerControllerDelegate {<br>        var parent: ImagePicker<br><br>        init(_ parent: ImagePicker) {<br>            self.parent = parent<br>        }<br><br>        func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {<br>            if let image = info[.originalImage] as? UIImage {<br>                parent.completion(image)<br>            }<br>            parent.presentationMode.wrappedValue.dismiss()<br>        }<br>    }<br>}</pre><p>We’ll use the sourceType binding to switch between the camera and the library.</p><p>Now, we’ll add a Classifierto handle the image uploading and return the classification results. I’m jumping around a little, but all this will come together in a few. Create a new file called Classifier.swift and add this in:</p><pre>import Foundation<br>import UIKit<br><br>struct Classifier {<br>    /// replace this with your dev machine IP address<br>    /// for testing with a physical device.<br>    private let host = &quot;localhost&quot;<br><br>    func classify(image: UIImage) async throws -&gt; [ClassifierResult] {<br>        // Ensure the URL is valid<br>        guard let uploadURL = URL(string: &quot;http://\(host):8080/classify&quot;) else {<br>            throw URLError(.badURL)<br>        }<br><br>        // Convert the image to JPEG data<br>        guard let imageData = image.jpegData(compressionQuality: 1.0) else {<br>            throw URLError(.unknown)<br>        }<br><br>        // Generate boundary string using a unique per-app string<br>        let boundary = &quot;Boundary-\(UUID().uuidString)&quot;<br><br>        // Create a URLRequest object<br>        var request = URLRequest(url: uploadURL)<br>        request.httpMethod = &quot;POST&quot;<br>        request.setValue(&quot;multipart/form-data; boundary=\(boundary)&quot;, forHTTPHeaderField: &quot;Content-Type&quot;)<br><br>        // Create multipart form body<br>        let body = createMultipartFormData(boundary: boundary, data: imageData, fileName: &quot;photo.jpg&quot;)<br>        request.httpBody = body<br><br>        // Perform the upload task<br>        let (data, response) = try await URLSession.shared.upload(for: request, from: body)<br><br>        // Check the response and throw an error if it&#39;s not a HTTPURLResponse or the status code is not 200<br>        guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>            throw URLError(.badServerResponse)<br>        }<br><br>        // Decode the data into an array of ClassifierResult<br>        return try JSONDecoder().decode([ClassifierResult].self, from: data)<br>    }<br><br>    /// Creates a multipart/form-data body with the image data.<br>    /// - Parameters:<br>    ///   - boundary: The boundary string separating parts of the data.<br>    ///   - data: The image data to be included in the request.<br>    ///   - fileName: The filename for the image data in the form-data.<br>    /// - Returns: A `Data` object representing the multipart/form-data body.<br>    private func createMultipartFormData(boundary: String, data: Data, fileName: String) -&gt; Data {<br>        var body = Data()<br><br>        // Add the image data to the raw http request data<br>        body.append(&quot;--\(boundary)\r\n&quot;)<br>        body.append(&quot;Content-Disposition: form-data; name=\&quot;file\&quot;; filename=\&quot;\(fileName)\&quot;\r\n&quot;)<br>        body.append(&quot;Content-Type: image/jpeg\r\n\r\n&quot;)<br>        body.append(data)<br>        body.append(&quot;\r\n&quot;)<br><br>        // Add the closing boundary<br>        body.append(&quot;--\(boundary)--\r\n&quot;)<br>        return body<br>    }<br><br>    struct ClassifierResult: Decodable, Identifiable {<br>        let id = UUID()<br>        var label: String<br>        var confidence: Float<br>    }<br>}<br><br>// Helper function to append string data to Data object<br>private extension Data {<br>    mutating func append(_ string: String) {<br>        if let data = string.data(using: .utf8) {<br>            append(data)<br>        }<br>    }<br>}</pre><p>Great! Now on to the UI. Back in ContentView , let&#39;s add an enum called RequestStatus to communicate to the user what is going on — this is an easy UX win.</p><pre>enum RequestStatus {<br>    case loading, success, idle, error<br>}</pre><p>Now, we’ll create a view model for ContentView that uses the newly created classifier to upload a photo to the server and share the results with the UI. This is also going to use the new <a href="https://developer.apple.com/documentation/observation">Observation framework</a> ⭐.</p><pre>extension ContentView {<br>    @Observable<br>    class ViewModel {<br>        var requestStatus: RequestStatus = .idle<br>        var results: [Classifier.ClassifierResult] = []<br><br>        private var classifier = Classifier()<br><br>        func upload(_ image: UIImage) {<br>            Task { @MainActor in<br>                do {<br>                    requestStatus = .loading<br>                    results.removeAll()<br>                    results = try await classifier.classify(image: image)<br>                    requestStatus = .success<br>                } catch {<br>                    print(error.localizedDescription)<br>                    requestStatus = .error<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>Now we need to add some state. This stuff should probably go in the view model, but for now, I’m going to add these as member vars to ContentView …</p><pre>// ContentView.swift<br>@State private var selectedImage: UIImage?<br>@State private var isImagePickerPresented = false<br>@State private var viewModel = ViewModel()<br>@State private var sourceType: UIImagePickerController.SourceType = .camera</pre><p>Alright, now we’ll do some more UI building. Replace the body variable with this:</p><pre>    var body: some View {<br>        VStack(spacing: 20) {<br>            HStack(spacing: 20) {<br>                if let image = selectedImage {<br>                    VStack {<br>                        Image(uiImage: image)<br>                            .resizable()<br>                            .scaledToFit()<br>                    }.padding()<br>                        .frame(maxHeight: 350)<br>                }<br>                List {<br>                    ForEach(viewModel.results, id: \.id) { result in<br>                        VStack(alignment: .leading) {<br>                            Text(result.label)<br>                                .font(.callout)<br>                            Text(formatAsPercentage(result.confidence))<br>                                .font(.caption2)<br>                        }<br>                    }<br>                }<br>            }<br>            Divider()<br>            HStack(spacing: 20) {<br>                actionButton()<br>                if viewModel.requestStatus == .loading {<br>                    ProgressView()<br>                }<br>            }<br>        }<br>        .sheet(isPresented: $isImagePickerPresented) {<br>            ImagePicker(sourceType: $sourceType) { image in<br>                self.selectedImage = image<br>            }<br>        }<br>    }</pre><p>And to address those compiler errors, add two new functions:</p><pre>// ContentView.swift<br>@ViewBuilder<br>private func actionButton() -&gt; some View {<br>    if let image = selectedImage {<br>        Button(&quot;Upload Image&quot;) {<br>            viewModel.upload(image)<br>        }.buttonStyle(.borderedProminent)<br>    } else {<br>        HStack(spacing: 20) {<br>            Button(&quot;Camera&quot;) {<br>                sourceType = .camera<br>                isImagePickerPresented = true<br>            }.buttonStyle(.bordered)<br>            Button(&quot;Photo Library&quot;) {<br>                sourceType = .photoLibrary<br>                isImagePickerPresented = true<br>            }.buttonStyle(.bordered)<br>        }.padding(.bottom, 20)<br>    }<br>}<br><br>// and<br><br>private func formatAsPercentage(_ value: Float) -&gt; String {<br>    String(format: &quot;%.2f%%&quot;, value * 100)<br>}</pre><p>Heck yeah, you guys. If everything has gone according to plan, you should now be able to create/select a picture, upload it to the server, classify the dominant object in the picture, and then display the classification results in the UI!</p><p>If you run into issues, please feel free to reference the source code, or leave a comment below.</p><p>I hope this project inspires you and gets the gears turning for your next ML project.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48809a853fae" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/deploy-coreml-models-on-the-server-with-vapor-48809a853fae">Deploy CoreML Models on the Server with Vapor</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Server-side Swift? Why not?]]></title>
            <link>https://medium.com/better-programming/server-side-swift-why-not-b04de4251f32?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b04de4251f32</guid>
            <category><![CDATA[macos]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 04:37:49 GMT</pubDate>
            <atom:updated>2024-04-10T03:57:48.765Z</atom:updated>
            <content:encoded><![CDATA[<h4>Let&#39;s build a real-time chatroom with Vapor and SwiftUI.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IaYXwNRA8Ev2jSrqUvYl5g.png" /></figure><p>Many associate Swift exclusively with mobile app development, often overlooking its potential on the server. The other day I thought, “Why not treat Swift like JavaScript/<a href="https://nodejs.org/en">Node.js</a> and use it server-side?” The truth is, Swift has been used on the server for many years. It has a rich ecosystem that includes the <a href="https://vapor.codes/">Vapor</a> web framework and has an active developer community.</p><p>One thing I like about Node.js is the ease of building real-time apps with WebSockets (WS), explicitly using the <a href="https://socket.io/">socket.io</a> framework. Building a simple chat room app with node, React (or whichever client-side JS framework you prefer) and socket.io is a breeze.</p><p>Let’s mix it up a bit.</p><p>For a fun intermediate project, let’s try building a simple web server using <a href="https://vapor.codes/">Vapor</a> and an iOS client using <a href="https://developer.apple.com/xcode/swiftui/">SwiftUI</a> to connect via <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API">WebSockets</a>.</p><p>In addition, we’ll try the new <a href="https://developer.apple.com/documentation/observation">Observation framework</a> ⭐, which sounds very cool and could help clean up a lot of fluff in our codebases.</p><h4>What We Are Going to Do</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ORsLt__VmUA4iyGM4xOlA.png" /></figure><p>Build a super minimal chatroom that enables messages sent from one connected client to appear in all connected clients.</p><h4>What We Are Not Going to Do</h4><p>Set up a way to differentiate between sender and receiver clients. For example, in iMessage, messages you send appear on the right side of the UI with a blue background, and messages you receive are displayed on the left side of the UI with a grey background. For real-world chat, this is an essential feature, but I am semi-lazy, so maybe we’ll add this in at a later time…</p><h4>Before We Start</h4><p>It’s also important to note that this POC may not necessarily adhere to best practices nor be totally thread-safe. It is a prototype after all.</p><p>If you want to skip all this and look at the code, or if you want to follow along, clone the repo: <a href="https://github.com/drewalth/swift-chatroom">https://github.com/drewalth/swift-chatroom</a>.</p><p>For the sake of brevity, I’m going to say “Refresh the app” quite a bit. This means selecting a scheme, either SwiftChatroom or App, and press cmd + r or build and run. Example, “Refresh the server” or “Refresh the iOS app”.</p><p>Okay, disclaimers over. Let’s jump in!</p><h4>System Requirements</h4><ul><li>Homebrew</li><li>macOS 14</li><li>Xcode 15</li></ul><h3>The Fun Part</h3><p>First, head over to <a href="https://vapor.codes/">https://vapor.codes/</a> and follow the installation instructions.</p><p>Let’s create a workspace to help keep things organized. Create a new folder called swift-chatroom and navigate into the directory.</p><pre>mkdir swift-chatroom &amp;&amp; cd swift-chatroom</pre><p>Open Xcode and go to File -&gt; New -&gt; Workspace. And create a new workspace called swift-chatroomin the swift-chatroom/ directory you just created.</p><p>Now, create the Vapor server.</p><pre>vapor new server -n</pre><p>In Xcode, add the server to the workspace. File -&gt; Add Package Dependencies -&gt; Add Local , select the new server directory and click open. It will take a second for Xcode to load all the other dependencies of Vapor. Once complete, Refresh the server.</p><p>Next, create the iOS client. File -&gt; New -&gt; Project . Select iOS, call it “SwiftChatroom” and add the project to the swift-chatroom workspace.</p><p>Select the SwiftChatroom scheme and run the app on the simulator of your choosing. To test the incoming message broadcasting, from Xcode run the app in a different simulator. Only one will have debug logging n’ things, but that’s okay for now.</p><p>Let&#39;s verify that the iOS app can communicate with the server. First, make a few small changes to the /hello route. Open Packages-&gt;server-&gt;Sources-&gt;App-&gt;routes.swift. Here, create a new structure called Greeting.</p><pre>struct Greeting: Content {<br>    var message: String<br>}</pre><p>And change the generated “hello” handler to this:</p><pre>app.get(&quot;hello&quot;) { req async -&gt; Greeting in<br>      Greeting(message: &quot;Hello world!&quot;)<br>}</pre><p>Refresh the App.</p><p>Now, in the iOS app, open ContentView.swift, add a State variable to store our decoded message.</p><pre>@State private var message: String = &quot;&quot;</pre><p>Replace the placeholder “Hello world!” in the Text view with our state variable. The VStack should look like this:</p><pre>VStack {<br>    Image(systemName: &quot;globe&quot;)<br>        .imageScale(.large)<br>        .foregroundStyle(.tint)<br>    Text(message)<br>}</pre><p>Cool. Now, let&#39;s write our HTTP request and call the server. Add a Greeting struct to match the response returned by the server and a function called fetchGreeting.</p><pre>func fetchGreeting() async throws -&gt; String {<br>    // Create the URL<br>    guard let url = URL(string: &quot;http://localhost:8080/hello&quot;) else {<br>        throw URLError(.badURL)<br>    }<br><br>    let session = URLSession.shared<br><br>    // Make an async request<br>    let (data, response) = try await session.data(from: url)<br><br>    // Check for HTTP response and status code<br>    guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>        throw URLError(.badServerResponse)<br>    }<br><br>    // Decode the response<br>    return try JSONDecoder().decode(Greeting.self, from: data).message<br>}<br><br>struct Greeting: Decodable {<br>    let message: String<br>}</pre><p>Call this function in a .task modifier on our VStack:</p><pre>.task {<br>    do {<br>        self.message = try await fetchGreeting()<br>    } catch {<br>        print(error)<br>    }<br>}</pre><p>Refresh the apps. If everything works as expected, you should see something like the UI from the generated boilerplate code on project creation…</p><p>Awesome! Now that our server and client are talking to each other let&#39;s set up our chatroom.</p><h3>Vapor + WebSocket Server</h3><p>To test this using a physical device, complete the following steps below. If you plan on using simulators only, skip the “Physical Device” bullets listed below.</p><h4>Physical Device</h4><ul><li>Update the Info.plist. Add the “App Transport Security Settings” dict, and in that, add “Allow Arbitrary Loads” and set to “YES”.</li><li>Get your dev machine’s IP address and set <a href="https://github.com/drewalth/swift-chatroom/blob/main/SwiftChatoom/SwiftChatoom/WebSocketManager.swift#L15">serverHost</a> to this value.</li></ul><blockquote>Heads up for physical device folks: if you get “Connection refused” errors when running the app, check to see if your Firewall allows your dev machine to accept incoming connections. See Settings.Network.Firewall.</blockquote><p>Okay, now let&#39;s set up our web socket. Vapor has <a href="https://docs.vapor.codes/advanced/websockets/">built-in support</a> for this which is pretty neat.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fn3p6JiIG0TzCU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fn3p6JiIG0TzCU%2Fgiphy-downsized-large.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fn3p6JiIG0TzCU%2Fgiphy-downsized-large.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="337" frameborder="0" scrolling="no"><a href="https://medium.com/media/7473f8a3ae6c564a473adf606af10db9/href">https://medium.com/media/7473f8a3ae6c564a473adf606af10db9/href</a></iframe><p>Open the routes.swift file and add the following “chat” route/socket that sends a message to the client when connected.</p><pre>//  app.get(&quot;hello&quot;) ... <br><br>app.webSocket(&quot;chat&quot;) { req, ws in<br>    ws.send(&quot;Connected!&quot;)<br>}</pre><p>Sweet! Now, we’ll set up the client-side stuff n’ give it a whirl. If you plan on testing this out with a physical device, edit the App scheme Run arguments to ensure your Vapor server is binding to 0.0.0.0 so it can accept connections from any IP address.</p><p>When you start your Vapor server, make sure you’re using:</p><pre>vapor run serve --hostname 0.0.0.0</pre><p>Or, if you’re not using the Vapor toolbox:</p><pre>swift run Run serve --hostname 0.0.0.0</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6-pyB2O0ofZdP8knIZVyQ.png" /></figure><h3>WebSocket Client</h3><p>In this POC we’ll use <a href="https://github.com/daltoniam/Starscream">Starscream</a> to communicate with the server. Add Starscream as a package dependency:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_hhKnYQKfnIADWHOO7J1g.png" /></figure><p>Next, we’ll add an Observable class to interface with the server. Create a new Swift file called WebSocketManager and paste in the following:</p><pre>import Starscream<br><br>@Observable<br>class WebSocketManager {<br>    /// Replace this value with your machine&#39;s IP address<br>    /// if you want to test using a physical device.<br>    private var serverHost = &quot;localhost&quot;<br>    <br>    private var socket: WebSocket!<br>    var isConnected = false<br>    var messages: [String] = []<br><br>    init() {<br>        setupWebSocket()<br>    }<br><br>    private func setupWebSocket() {<br>        var request = URLRequest(url: URL(string: &quot;ws://\(serverHost):8080/chat&quot;)!)<br>        request.timeoutInterval = 5<br>        socket = WebSocket(request: request)<br>        socket.delegate = self<br>    }<br><br>    func connect() {<br>        socket.connect()<br>    }<br><br>    func disconnect() {<br>        socket.disconnect()<br>    }<br><br>    func send(_ message: String) {<br>        socket.write(string: message)<br>    }<br>}<br><br>extension WebSocketManager: WebSocketDelegate {<br>    func didReceive(event: Starscream.WebSocketEvent, client: Starscream.WebSocketClient) {<br>        switch event {<br>        case .connected(_):<br>            DispatchQueue.main.async {<br>                self.isConnected = true<br>            }<br>        case .disconnected(_, _):<br>            DispatchQueue.main.async {<br>                self.isConnected = false<br>            }<br>        case .text(let string):<br>            DispatchQueue.main.async {<br>                self.messages.append(string)<br>            }<br>        // ... handle other cases as needed<br>        default:<br>            break<br>        }<br>    }<br>}</pre><p>Next, connect the WebSocketManager to the UI and create a more chatroom-like design. Replace the ContentView struct with this:</p><pre>struct ContentView: View {<br>    @State private var webSocketManager = WebSocketManager()<br>    @State private var message: String = &quot;&quot;<br><br>    var body: some View {<br>        VStack(spacing: 20) {<br>            List(webSocketManager.messages, id: \.self) { msg in<br>                Text(msg)<br>            }<br><br>            HStack {<br>                TextField(&quot;Enter message...&quot;, text: $message)<br>                    .textFieldStyle(RoundedBorderTextFieldStyle())<br><br>                Button(&quot;Send&quot;) {<br>                    webSocketManager.send(message)<br>                    message = &quot;&quot;<br>                }<br>            }<br>            .padding()<br>        }<br>        .onAppear {<br>            webSocketManager.connect()<br>        }<br>        .onDisappear {<br>            webSocketManager.disconnect()<br>        }<br>    }<br>}</pre><p>Heck yeah. We’ve done a lot for the client, but our server isn&#39;t very capable. Let’s flush it out a bit.</p><h3>Back to the Server</h3><p>So far our server is only capable of notifying the client when it is connected. Next, we’ll add the ability to broadcast messages. To do this, we first need to keep track of all connected clients. In routes.swift, add this new variable outside of the func routes() scope.</p><pre>var connectedClients: [UUID: WebSocket] = [:]</pre><p>Now replace the app.webSocket(“chat”) handler with this:</p><pre>    app.webSocket(&quot;chat&quot;) { _, ws in<br>        ws.send(&quot;Connected!&quot;)<br><br>        // Generate a unique ID for the connected client<br>        let clientId = UUID()<br><br>        // Add the new WebSocket connection to our dictionary<br>        connectedClients[clientId] = ws<br><br>        // Handle when a client disconnects<br>        ws.onClose.whenComplete { _ in<br>            connectedClients[clientId] = nil<br>        }<br><br>        // Listen for messages from the client<br>        ws.onText { _, text in<br>            // Broadcast the message to all connected clients<br>            for client in connectedClients.values {<br>                client.send(text)<br>            }<br>        }<br>    }</pre><p>Alright. Now, let&#39;s try running everything all together. Refresh the server then refresh all the clients, physical or simulated, and try sending some messages! If everything is working as expected, you should be able to send a message from one client and immediately receive it in all the others.</p><p>In conclusion, I’m really impressed with how easy it was to set this whole thing up.</p><p>However, like Node.js, it will take some time before server-side adoption is more prevalent in the community. Like every other language or framework, each has its use cases. This prototype illustrates how easy it is to create a real-time iOS app and server using only the Swift programming language — a self-categorized client-side-exclusive language.</p><p>I hope you found this project enjoyable and gets the wheels spinning for your next project!</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b04de4251f32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/server-side-swift-why-not-b04de4251f32">Server-side Swift? Why not?</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decodable SwiftData]]></title>
            <link>https://medium.com/better-programming/decodable-swiftdata-a-proof-of-concept-for-building-offline-first-ios-apps-5c5434ea61b5?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c5434ea61b5</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[offline]]></category>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[software]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Tue, 03 Oct 2023 22:20:24 GMT</pubDate>
            <atom:updated>2023-12-14T02:29:02.203Z</atom:updated>
            <content:encoded><![CDATA[<h4>A proof-of-concept for building offline-first iOS apps with Codable conforming models</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KIEsk10d2rrfRJ-Zf-4yaw.png" /><figcaption>Our final prototype | screenshot by author</figcaption></figure><p>Since Apple announced the new <a href="https://developer.apple.com/xcode/swiftdata/">SwiftData</a> framework at WWDC23, I’ve been SUPER eager to try it out. It’s a new framework that matches SwiftUI’s style and makes working with persistent data (CoreData) much easier. Now that it&#39;s out of beta, I spent an hour messing around with it and put together a quick proof-of-concept using this brand-spanking-new framework.</p><p>I specifically wanted to see how easy it would be to conform a persistent data model to the <a href="https://developer.apple.com/documentation/swift/codable">Codable</a> protocol to make working with remote and local persisted data easier.</p><p>The following approach could be helpful if you’re building an offline-capable iOS app that works with remote data, persists on the device, and syncs with the server when connected to the internet.</p><h3>The Problem</h3><p>Traditionally, when building an iOS app that needs to work with remote data and persist that data on the device, we would have to do a lot of stuff. Some of it includes creating the CoreData model and mirror structures that conform to Decodable. For example, if we have a CoreData model called Person that looks like this —</p><pre>class Person: NSManagedObject {<br>    @NSManaged var id: Int<br>    @NSManaged var name: String<br>    @NSManaged var age: Int<br>}</pre><p>we would also need to create a struct that mirrors this model when decoding our remote data. That will look like this:</p><pre>struct PersonRemote: Codable {<br>    let id: Int<br>    let name: String<br>    let age: Int<br>}</pre><p>If your model has a ton of member variables, this could become cumbersome and create errors. Also, this approach isn&#39;t the driest. What if we could define our models once and be good to go?</p><p>We can.</p><p>Before we start, it’s worth noting that a little duplication is okay, especially if it makes things easier to work with and maintain. We will see how “dry” we can get our models with SwiftData.</p><p><strong>Note</strong>: I also want to emphasize that the app we’re about to build is a <em>prototype </em>and may not necessarily adhere to “best practices” nor be totally thread-safe.</p><h3>Previous Approach</h3><p>As proposed in <a href="https://medium.com/better-programming/decodable-coredata-a-proof-of-concept-for-building-offline-first-ios-apps-f247b3ce6a27">Decodable CoreData</a>, we could use the Codable protocol to decode our remote data into our CoreData models. This was great because we didn’t have to write a lot of duplicate code and could use the same model for CoreData and decoding our remote data. This approach works. However, it has the following notable drawbacks:</p><ul><li>Context/thread safety is very fragile.</li><li>Too many “hacky” workarounds related to JSONDecoder and JSONEncoder</li></ul><h3>SwiftData Approach</h3><p>Like SwiftUI, SwiftData is declarative and uses many of the same concepts. For example, we can declare our persistent data model like this:</p><pre>import SwiftData<br><br>@Model<br>struct Person {<br>    let id: Int<br>    let name: String<br>    let age: Int<br>}</pre><p>Boom. That’s it. We don’t need to create a CoreData model with the Xcode UI or anything. SwiftData will automatically create the persisted model for us.</p><h3>The Fun Part</h3><p>OK, now that we’ve got an idea of SwiftData and the problem we’re trying to solve, let’s start coding!</p><p>If you want to skip all of this, I’ve put together a sample application with the final code. You can find it on <a href="https://github.com/drewalth/SwiftDataExploration">GitHub</a>.</p><h4><strong>Prototype features</strong></h4><ul><li>Fetch remote data</li><li>Persist remote data on the device</li><li>Sync local data with remote data source</li></ul><p>It’s important to note that for the scope of this POC, we will not build functionality that supports local posts or syncing them with a remote server. The remote server is the source of truth!</p><h3>Project Setup</h3><h4><strong>System Requirements</strong></h4><ul><li>Xcode 15</li><li>iOS 17 SDK</li><li>Nodejs LTS (currently v18)</li></ul><p>First, we need to create a new Xcode project.</p><p>Open Xcode.</p><p>Click Create New Project and select iOS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6OynqjwsohrryWUiVla_tQ.png" /></figure><p>Next, I’m going to call mine SwifDataExploration. I will also select SwiftUI as the user interface and SwiftData as the storage option. This will add a few things to our project, including a default model called Item.</p><p>We’ll delete this later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_T_yH7asYmwOq2VWicbFqA.png" /></figure><h3>Remote Data</h3><p>Next, we need to create a remote data source. For this example, we will use a mock API that returns a list of posts. For our server, we’ll use <a href="https://www.npmjs.com/package/json-server">json-server</a>.</p><p>From the project root, run the following commands:</p><pre>npm init -y<br>npm install --save-dev json-server</pre><p>Next, create a file called db.json in the project root, and add the following:</p><pre>{<br>  &quot;posts&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;Post 1&quot;,<br>      &quot;author&quot;: &quot;Johnny Appleseed&quot;<br>    }<br>  ]<br>}</pre><p>Next, add this start script to the package.json file that will run the mock server:</p><pre>{<br>&quot;scripts&quot;: {<br>  &quot;start&quot;: &quot;json-server --watch db.json&quot;<br>  } <br>}</pre><p>Now, open the terminal, navigate to the project root, and run npm start to bring up the dev API. To verify this works, open your browser and go to localhost:3000/posts. You should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZVRPWOKD2FtPQ3AzushfQ.png" /></figure><h3>Local Data Model</h3><p>Next, we need to create our local data model. Create a new file called PostModel that contains the following:</p><pre>// PostModel.swift<br>import SwiftData<br><br>@Model<br>class Post {<br>    let id: Int<br>    let title: String<br>    let author: String<br>}</pre><p>Now, let’s add this model to our schema. In the SwiftDataExplorationApp.swift file, you’ll see the following variable:</p><pre>    var sharedModelContainer: ModelContainer = {<br>        let schema = Schema([<br>            Item.self,<br>        ])<br>        let modelConfiguration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: false)<br><br>        do {<br>            return try ModelContainer(for: schema, configurations: [modelConfiguration])<br>        } catch {<br>            fatalError(&quot;Could not create ModelContainer: \(error)&quot;)<br>        }<br>    }()</pre><p>Replace Item.self with Post.self.</p><p>Now, in the ContentView.swift file, replace the Item model with Post. Here’s what that looks like:</p><pre>@Query private var items: [Item]<br><br>// replace with <br><br>@Query private var items: [Post]</pre><p>Fix the compiler errors that will pop up in the ForEach and do the same in for the preview. Your code should look like this:</p><pre>#Preview {<br>    ContentView()<br>        .modelContainer(for: Item.self, inMemory: true)<br>}<br><br>// replace with<br><br>#Preview {<br>    ContentView()<br>        .modelContainer(for: Post.self, inMemory: true)<br>}</pre><p>Let’s remove the boilerplate code, including addItem and deleteItems functions and the .onDelete and .toolbar modifiers.</p><p>Great. Now, we have our local data model setup and UI components for the scope of the POC. Next, we need to fetch our remote data.</p><h3>Fetching Remote Data</h3><p>Before fetching and decoding our remote data, our model must conform to the Codable protocol (really just Decodable). We can do this by making a few adjustments to our Post model:</p><pre>@Model<br>class Post: Codable {<br>    // other stuff...<br>    <br>    required init(from decoder: Decoder) throws {<br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        self.id = try container.decode(Int.self, forKey: .id)<br>        self.title = try container.decode(String.self, forKey: .title)<br>        self.author = try container.decode(String.self, forKey: .author)<br>    }<br><br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(self.id, forKey: .id)<br>        try container.encode(self.title, forKey: .title)<br>        try container.encode(self.author, forKey: .author)<br>    }<br><br>    enum CodingKeys: CodingKey {<br>        case id, title, author<br>    }<br>}</pre><p>Incredible. In just a few short steps, we’ve created our local data model and made it conform to Codable without any goofy hacks.</p><p>Create a new file called PostService.swift with a struct called PostService, and add the following method:</p><pre>    static func getPosts() async throws -&gt; [Post] {<br>        let url = URL(string: &quot;http://localhost:3000/posts&quot;)!<br><br>        let session = URLSession.shared<br><br>        // Make the network request<br>        let (data, response) = try await session.data(from: url)<br><br>        // Check for HTTP errors<br>        guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else {<br>            throw URLError(.badServerResponse)<br>        }<br><br>        // Decode the data into an array of Post<br>        let decoder = JSONDecoder()<br>        let posts = try decoder.decode([Post].self, from: data)<br><br>        return posts<br>    }</pre><p>Now, in the ContentView.swift file, add a .task modifier to the NavigationSplitView:</p><pre>NavigationSplitView {<br>    // stuff<br>}.task {<br>    do {<br>        let posts = try await PostService.getPosts()<br>        print(posts)<br>    } catch {<br>        print(error.localizedDescription)<br>    }<br>}</pre><p>Run the app, and you should see the following in the console:</p><pre>[SwiftDataExploration.Post(id: 1, title: &quot;Post 1&quot;, author: &quot;Johnny Appleseed&quot;)]</pre><h3>Persist Remote Data</h3><p>Now that we have our remote/local data model set up, let&#39;s save it to the device.</p><p>Create two new files: ModelRepository.swift and PostRepository.swift.</p><p>The ModelRepository.swift file will provide a generic interface for our local models that can be used inside and outside SwiftUI views. Future state thinking, but whatever.</p><p>Inside the ModelRepository.swift file, add the following:</p><pre>import SwiftData<br><br>struct ModelRepository&lt;Model: PersistentModel&gt; {<br>    private let context: ModelContext<br><br>    init(context: ModelContext) {<br>        self.context = context<br>    }<br>    <br>    func getAll() throws -&gt; [Model] {<br>        let params = FetchDescriptor&lt;Model&gt;()<br>        let result = try context.fetch(params)<br>        return result<br>    }<br>}</pre><p>Now, in the PostRepository.swift file, we’ll create an interface for our Post model that uses the ModelRepository, then add a sync method to sync our local data with the remote data source.</p><p>Here’s the code:</p><pre>import SwiftData<br><br>struct PostRepository {<br>    private let repository: ModelRepository&lt;Post&gt;<br><br>    init(context: ModelContext) {<br>        self.repository = ModelRepository(context: context)<br>    }<br><br>    func sync(_ remotePosts: [Post]) throws -&gt; [Post] {<br>        do {<br>            var localPosts = try repository.getAll()<br>            print(localPosts)<br>        } catch {<br>            print(error.localizedDescription)<br>        }<br>    }<br>}</pre><p>Back in the ContentView.swift file, let’s adjust our .task modifier to use the PostRepository. Here’s what that looks like:</p><pre>.task {<br>    do {<br>        let postRepository = PostRepository(context: modelContext)<br>        let remotePosts = try await PostService.getPosts()<br>        postRepository.sync(remotePosts)<br>    } catch {<br>        print(error.localizedDescription)<br>    }<br>}</pre><p>Run the app. You should see an empty array in the console. That’s because we haven’t added any posts to our local data store yet. Let’s do that now.</p><p>In ModelRepository.swift, add the following methods:</p><pre>/// Add models to the local data store<br>func create(_ models: [Model]) {<br>    for model in models {<br>        context.insert(model)<br>    }<br>}<br><br>/// Save changes made to the local data store<br>func save() throws {<br>    if context.hasChanges {<br>        try context.save()<br>    }<br>}</pre><p>Then, back in the PostRepository.swift file, add the following to the sync method:</p><pre>func sync(_ remotePosts: [Post]) throws -&gt; [Post] {<br>    do {<br>        var localPosts = try repository.getAll()<br>        print(localPosts)<br>        repository.create(remotePosts)<br>        <br>        try repository.save()<br>        <br>        // verify that the posts were saved<br>        localPosts = try repository.getAll()<br>        print(localPosts)<br>    } catch {<br>        print(error.localizedDescription)<br>    }<br>}</pre><p>Awesome! Now run the app, and you should see some posts in the console and the UI. Stop the app and restart it.</p><p>You should now see two posts with the same title: “Post 1.”</p><p>This happened because we’re not specifying a unique identifier (or primary key) for our posts. Let’s fix that now. In the PostModel.swift file, update the id property to the following:</p><pre>@Attribute(.unique)<br>var id: Int</pre><p>Now, in the simulator, delete the app. Then, run it, close it, and rerun it.</p><p>You should now see only one post titled “Post 1.”</p><p>Let’s verify this works by adding a new post to our remote data source. In the db.json file, add a new post:</p><pre>{<br>  &quot;posts&quot;: [<br>    {<br>      &quot;id&quot;: 1,<br>      &quot;title&quot;: &quot;Post 1&quot;,<br>      &quot;author&quot;: &quot;Johnny Appleseed&quot;<br>    },<br>    {<br>      &quot;id&quot;: 2,<br>      &quot;title&quot;: &quot;Post 2&quot;,<br>      &quot;author&quot;: &quot;Johnny Appleseed&quot;<br>    }<br>  ]<br>}</pre><p>Now run the app, and you should see two posts in the console and in the UI :party_parrot.</p><h3>Update Local Data With Remote Data</h3><p>Now that our local data store is syncing with our remote data source, let’s update the PostRepository to update existing posts. To do this, we’ll create a function called `updateLocalPosts` that will compare the remote posts with the local posts.</p><p>We’ll also need to make our Post model conform to the Equatable protocol to compare posts.</p><pre>// PostModel.swift<br><br>@Model<br>class Post: Codable, Equatable {<br>    // other stuff...    <br>}</pre><p>Now, in the PostRepository.swift file, add the following method:</p><pre>func updateLocalPosts(with remotePosts: [Post], in localPosts: inout [Post]) {<br>    for (index, localPost) in localPosts.enumerated() {<br>        if let matchingRemotePost = remotePosts.first(where: { $0.id == localPost.id }),<br>           localPost != matchingRemotePost<br>        {<br>            localPosts[index] = matchingRemotePost<br>        }<br>    }<br>}</pre><p>Then, let&#39;s call it in the sync method and remove the verifying print statement. We’ll also want to call updateLocalPosts before we create any new posts.</p><pre>func sync(_ remotePosts: [Post]) throws -&gt; [Post] {<br>    do {<br>        var localPosts = try repository.getAll()<br>        updateLocalPosts(with: remotePosts, in: &amp;localPosts)<br>        repository.create(remotePosts)<br>        <br>        try repository.save()<br>    } catch {<br>        print(error.localizedDescription)<br>    }<br>}</pre><p>Now, let&#39;s verify this is working as expected. In the db.json file, update the title of the first post to “Post 1 Updated.” Then, run the app.</p><p>You should see the new title in the UI.</p><p>So. cool.</p><h3>Delete Local Data</h3><p>We want to ensure that if a post is no longer returned from the server, it is considered stale and should be removed from the local data store.</p><p>In ModelReposity.swift, add the following deleteEntities method:</p><pre>func deleteEntities(_ models: [Model]) {<br>    for model in models {<br>        context.delete(model)<br>    }<br>}</pre><p>And now, in PostReposity.swift, let&#39;s use the previous method by adding it to this new method:</p><pre>private func checkPostsForDeletion(localPosts: [Post], remotePosts: [Post]) -&gt; [Post] {<br>    var postsToDelete: [Post] = []<br><br>    let remotePostIds = Set(remotePosts.map { $0.id })<br><br>    for localPost in localPosts {<br>        if !remotePostIds.contains(localPost.id) {<br>            postsToDelete.append(localPost)<br>        }<br>    }<br><br>    return postsToDelete<br>}</pre><p>And call it in the sync method before updateLocalPosts and create.</p><p>The sync function should look like this:</p><pre>// load local posts<br>var localPosts = try repository.getAll()<br><br>// first delete stale posts<br>let postsToDelete = checkPostsForDeletion(localPosts: localPosts, remotePosts: remotePosts)<br>repository.deleteEntities(postsToDelete)<br>updateLocalPosts(with: remotePosts, in: &amp;localPosts)<br>repository.create(remotePosts)<br>try repository.save()</pre><h3>User Experience</h3><p>Let&#39;s make a few more edits to implement some easy UX wins. Again, to reiterate, this is a prototype and far from perfect.</p><p>First, let&#39;s make an enum called RequestStatus to help us communicate to the end user what is happening under the hood.</p><pre>// Types.swift<br>enum RequestStatus {<br>    case idle, loading, success, error<br>}</pre><p>Now, back in ContentView.swift, let&#39;s add a @State property to keep track of the request status and update the .task. Here’s what the code looks like:</p><pre>@State private var requestStatus: RequestStatus = .idle <br><br>// and the modifier<br><br>.task {<br>    do {<br>        requestStatus = .loading<br>        <br>        let postRepository = PostRepository(context: modelContext)<br>        let remotePosts = try await PostService.getPosts()<br>        await postRepository.sync(remotePosts)<br><br>        requestStatus = .success<br>    } catch {<br>        print(error.localizedDescription)<br>        requestStatus = .error<br>    }<br>}</pre><p>Now, let&#39;s add views to the List that will display the request status. Your file should look like this:</p><pre>List {<br>    switch requestStatus {<br>    case .loading:<br>        ProgressView()<br>    case .error:<br>        Text(&quot;error&quot;)<br>    default:<br>        ForEach(items) { item in<br>            NavigationLink {<br>                Text(item.title)<br>            } label: {<br>                Text(item.title)<br>            }<br>        }<br>    }<br>}</pre><p>To simulate long-running requests, we can add a delay to the PostService’s getPosts method:</p><pre>try await Task.sleep(nanoseconds: 3_000_000_000)</pre><p>Now, run the app. You should see the three-second progress view before the posts are displayed.</p><h3>Offline Support</h3><p>Now that our local data store is syncing with our remote data source, let’s add some offline support. We want to fetch posts if the device is connected to the internet. Otherwise, we want to display the posts from the local data store.</p><p>Let&#39;s create a new file called NetworkMonitor.swift, and add the following:</p><pre>import Network<br>import SwiftUI<br><br>class NetworkMonitor: ObservableObject {<br>    private var monitor: NWPathMonitor<br>    private var queue: DispatchQueue<br><br>    @Published var isConnected: Bool = true<br><br>    init() {<br>        monitor = NWPathMonitor()<br>        queue = DispatchQueue(label: &quot;NetworkMonitor&quot;)<br><br>        monitor.pathUpdateHandler = { [weak self] path in<br>            if path.status == .satisfied {<br>                DispatchQueue.main.async {<br>                    self?.isConnected = true<br>                }<br>            } else {<br>                DispatchQueue.main.async {<br>                    self?.isConnected = false<br>                }<br>            }<br>        }<br><br>        monitor.start(queue: queue)<br>    }<br>}</pre><p>Now, let&#39;s add a @StateObject property to the app entry SwiftDataExplorationApp:</p><pre>@StateObject var networkMonitor = NetworkMonitor()<br><br>// and inject the value<br><br>ContentView()<br>    .environmentObject(networkMonitor)</pre><p>Now, back in the ContentView.swift file, let&#39;s add a @EnvironmentObject property to the ContentView and add a check to the .task modifier:</p><pre>@EnvironmentObject private var network: NetworkMonitor<br><br>// and<br><br>.task {<br>     do {<br>        guard network.isConnected else { return }<br><br>        requestStatus = .loading<br><br>        let postRepository = PostRepository(context: modelContext)<br><br>        let remotePosts = try await PostService.getPosts()<br>        await postRepository.sync(remotePosts)<br><br>        requestStatus = .success<br>    } catch {<br>        print(error.localizedDescription)<br>        requestStatus = .error<br>    }<br>}</pre><p>Disconnect from the internet and run the app to test whether this works. The locally stored posts should be displayed immediately.</p><p>Well, that’s all folks!</p><p>We now have a simple offline-first app. Add, edit, and remove items from db.json to check out all the neat stuff we made.</p><p>Again, this is far from perfect, but it does serve as an OK starting point/thought starter.</p><p>I’m looking forward to trying out more complex functionality with SwiftData.</p><p>If you have any questions or feedback, please feel free to comment.</p><p>Cheers!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c5434ea61b5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/decodable-swiftdata-a-proof-of-concept-for-building-offline-first-ios-apps-5c5434ea61b5">Decodable SwiftData</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generate OpenAPI Specification from ORM Models]]></title>
            <link>https://medium.com/@drewalth/harnessing-the-power-of-the-openapi-specification-boosting-productivity-and-developer-experience-2ffe5c0055ad?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ffe5c0055ad</guid>
            <category><![CDATA[documentation]]></category>
            <category><![CDATA[open-api]]></category>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[generator]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Tue, 04 Jul 2023 19:54:03 GMT</pubDate>
            <atom:updated>2023-07-05T01:46:14.039Z</atom:updated>
            <content:encoded><![CDATA[<h4>Kickstart your API documentation journey</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*QC6auQNp2eLMxrSg" /><figcaption>Photo by <a href="https://unsplash.com/@f12r?utm_source=medium&amp;utm_medium=referral">Fahim Muntashir</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>The OpenAPI Specification (OAS), formerly known as the Swagger Specification, has emerged as a key tool for building and integrating APIs (Application Programming Interfaces). This standard, governed by the OpenAPI Initiative under the Linux Foundation, defines a programming language-agnostic interface for RESTful APIs. Specifying an API&#39;s details in a structured format fosters seamless integration and collaboration between various systems and components. This article will explore the benefits of adopting the OpenAPI Specification, illustrate how it improves developer productivity and the overall developer experience, and plug a tool I’ve written to help get you started.</p><h3>TLDR</h3><p>OpenAPI spec is incredibly helpful. I’ve created a CLI to help generate an OpenAPI spec file from your ORM model definitions. Currently, this only supports Laravel Eloquent, Sequelize, or SpringBoot. You can check out the CLI tool here: <a href="https://github.com/drewalth/openapi-generator">https://github.com/drewalth/openapi-generator</a>. Or clone the repo to take a gander:</p><pre>git clone https://github.com/drewalth/openapi-generator.git</pre><p>PRs and feedback are welcome!</p><h3>OpenAPI Specification: A Brief Overview</h3><p>OpenAPI Specification is a document, typically in JSON or YAML format, that details all the aspects of an API. This includes endpoints, request/response formats, authentication, and more. It serves as a contract between the API and its consumers, ensuring that both parties clearly understand the API’s functionalities and expected behavior.</p><h3>Benefits of the OpenAPI Specification</h3><h4>Improved Documentation</h4><p>OpenAPI Specification acts as a source of documentation for the API. Tools like Swagger UI can generate interactive documentation from an OpenAPI document. This keeps the documentation consistent with the code and provides a visual, user-friendly interface for understanding the API.</p><h4>Enhanced Collaboration</h4><p>OpenAPI Specification facilitates collaboration among front-end developers, back-end developers, and QA teams. By having a single source of truth, teams can work simultaneously on different aspects of the application without misunderstandings.</p><h4>Faster Development</h4><p>Developers can use the OpenAPI Specification to automatically generate boilerplate code for clients and servers in different languages using tools such as Swagger Codegen. This speeds up the development process, allowing developers to focus on implementing business logic.</p><h4>Simplified Testing</h4><p>By adopting the OpenAPI Specification, automated testing can be streamlined. Tools like Dredd allow developers to validate that the API complies with its specification, thus ensuring consistency and reliability.</p><h3>Real-World Examples</h3><h4>Stripe</h4><p>Stripe, a renowned payment processing company, has adopted the OpenAPI Specification to ensure the consistency and reliability of its APIs. This has enabled Stripe to provide robust, well-documented APIs that have been critical in gaining the trust of developers and companies.</p><h4>Slack</h4><p>Slack, a popular team collaboration tool, uses the OpenAPI Specification to streamline its API development. The clear documentation and client libraries generated from the OpenAPI Specification allow developers to integrate Slack into their applications easily.</p><h4>Ayden</h4><p>Adyen, a global payment company, utilizes the OpenAPI Specification to enhance the developer experience. The interactive documentation enables developers to understand and integrate Adyen’s functionalities into their e-commerce solutions.</p><h3>Conclusion</h3><p>Adopting the OpenAPI Specification is beneficial for both API providers and consumers. Providing clear documentation, improving collaboration, speeding up development, and simplifying testing, significantly enhances developer productivity and experience. As Stripe, Slack, and Adyen exemplified, the OpenAPI Specification is an invaluable asset for building robust, scalable, and efficient APIs in the modern world.</p><p>Getting started with Openapi spec can be daunting, especially if you have much to document. (shameless plug incoming). To jumpstart the process, I’ve created a simple CLI to help generate an OpenAPI spec file. This only works if you use an orm like Laravel Eloquent, Sequelize, or SpringBoot. You can check out the CLI tool here: <a href="https://github.com/drewalth/openapi-generator">https://github.com/drewalth/openapi-generator</a></p><p>PRs welcome!</p><p>Cheers</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ffe5c0055ad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decodable CoreData: A Proof-of-Concept for Building Offline-First iOS Apps]]></title>
            <link>https://medium.com/better-programming/decodable-coredata-a-proof-of-concept-for-building-offline-first-ios-apps-f247b3ce6a27?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/f247b3ce6a27</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 22:24:28 GMT</pubDate>
            <atom:updated>2023-07-05T03:57:34.583Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8zqgWI7INMpRYoF1" /><figcaption>Photo by <a href="https://unsplash.com/@anniespratt?utm_source=medium&amp;utm_medium=referral">Annie Spratt</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>You’re building an iOS app with a truckload of data coming in and out. You also want to make this data available even if your users are off the grid. Where do you put it? CoreData, baby!</p><p>But then, you have to think about syncing with the outside world — your remote server. You don’t want your users to pull their hair out when the internet takes a break, right? Let’s get them happy by building an offline-first app with CoreData.</p><p>I recommend <a href="https://github.com/drewalth/CoreDataExploration">cloning the project</a> to help follow along.</p><pre>/**<br> * @note before getting started, this article assumes a general <br> * familiarity with Swift, CoreData and SwiftUI. If you are new to either of these, <br> * I HIGHLY recommend checking out the Swift course at codecademy.com,<br> * and Paul Hudson&#39;s hackingwithswift.com<br> */</pre><h3>Goals</h3><ul><li>Define the data model once. No defining our CoreData entities and mirror structs to decode JSON and then create/update entities.</li><li>Offline Capable</li></ul><h3>CoreData and Remote Data</h3><p>CoreData is like your home — cozy, and all your stuff is there. Remote data is like the grocery store; you go there to get fresh stuff. Problem? Imagine having to go to the store every time you need a coffee. Painful! Plus, sometimes the store is closed (read: no internet), and you get caffeine-deprived. No bueno! So, let’s bridge this gap with a cool hack.</p><p>🔮 Magic Spell: <em>Codable Protocol</em></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12NUbkX6p4xOO4%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12NUbkX6p4xOO4%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F12NUbkX6p4xOO4%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="398" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6d57f4067e20f622abd783ff7bfe8e2/href">https://medium.com/media/c6d57f4067e20f622abd783ff7bfe8e2/href</a></iframe><p>The <a href="https://developer.apple.com/documentation/swift/codable">Codable protocol</a> is like a magical potion that helps us decode and encode JSON. This is great for ephemeral data, but what if you want to save that data on a user&#39;s device? Making NSManagedObjects conform to Codable is a little tricky.</p><p>First, we must give our magical potion the correct context and a sense of direction.</p><pre>extension CodingUserInfoKey {<br>    static let managedObjectContext = CodingUserInfoKey(rawValue: &quot;managedObjectContext&quot;)!<br>}</pre><p>Next, we’ll create a CoreDataJSONDecoder helper to decode incoming JSON in the CoreData container view context. Remember those decoder rings in cereal boxes? This is like that, but way cooler. Our CoreDataJSONDecoder is the decoder ring that knows how to read secret messages (JSON data) and magically turn them into CoreData objects.</p><pre>struct CoreDataJSONDecoder {<br>    let decoder: JSONDecoder<br><br>    init() {<br>        let decoder = JSONDecoder()<br>        decoder.userInfo[CodingUserInfoKey.managedObjectContext] = PersistenceController.shared.container.viewContext<br>        self.decoder = decoder<br>    }<br><br>    enum DecoderConfigurationError: Error {<br>        case missingManagedObjectContext<br>    }<br>}</pre><p>Our decoder is now tuned into CoreData’s frequency; thanks to that managedObjectContext we gave it.</p><p>Next, we need to create our CoreData entity and make it conform to Codable.</p><pre>class ItemEntity: NSManagedObject, Codable {<br>    required convenience init(from decoder: Decoder) throws {<br>        guard let context = decoder.userInfo[CodingUserInfoKey.managedObjectContext] as? NSManagedObjectContext else {<br>            throw CoreDataJSONDecoder.DecoderConfigurationError.missingManagedObjectContext<br>        }<br>        self.init(context: context)<br>        <br>        let container = try decoder.container(keyedBy: CodingKeys.self)<br>        let uuidString = try container.decode(String.self, forKey: .id)<br>        id = UUID(uuidString: uuidString)<br>        title = try container.decode(String.self, forKey: .title)<br>        subtitle = try container.decode(String.self, forKey: .subtitle)<br>    }<br><br>    func encode(to encoder: Encoder) throws {<br>        var container = encoder.container(keyedBy: CodingKeys.self)<br>        try container.encode(title, forKey: .title)<br>        try container.encode(subtitle, forKey: .subtitle)<br>        try container.encode(id, forKey: .id)<br>    }<br>}</pre><p>Our CoreData model now wears the Codable cape. It can change into JSON and back like it’s no big deal.</p><p>It&#39;s also important to note the configuration of our CoreData entity. See the inspector on the right side of the following screenshot.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m1uyXm9Of-ojoBJTnlsvSQ.png" /></figure><p>Let&#39;s set up a super simple network layer to interact with our REST API. We’re going to use Alamofire in this example.</p><pre>import Alamofire<br>import Foundation<br><br>typealias NetworkError = AFError<br><br>enum RequestStatus {<br>    case loading, success, failure<br>}<br><br>struct NetworkManager {<br>    private let baseUrl = &quot;http://localhost:3000&quot;<br>    private let decoder = CoreDataJSONDecoder().decoder<br><br>    struct ResponseMessage: Decodable {<br>        let message: String<br>    }<br><br>    func get&lt;Output: Decodable&gt;(_ url: String,<br>                                output _: Output.Type,<br>                                completion: @escaping (Result&lt;Output, NetworkError&gt;) -&gt; Void)<br>    {<br>        AF.request(baseUrl + url).validate().responseDecodable(of: Output.self, decoder: decoder) { response in<br><br>            completion(response.result)<br>        }<br>    }<br><br>    func post&lt;Input: Encodable, Output: Decodable&gt;(_ url: String,<br>                                                   input: Input,<br>                                                   output _: Output.Type,<br>                                                   completion: @escaping (Result&lt;Output, NetworkError&gt;) -&gt; Void)<br>    {<br>        AF.request(baseUrl + url,<br>                   method: .post,<br>                   parameters: input,<br>                   encoder: .json,<br>                   headers: [<br>                       .init(name: &quot;Content-Type&quot;, value: &quot;application/json&quot;),<br>                   ])<br>                   .validate()<br>                   .responseDecodable(of: Output.self, decoder: decoder) { response in<br>                       completion(response.result)<br>                   }<br>    }<br>}</pre><p>Next, let&#39;s create a view to see a list of our ItemEntities.</p><pre>struct ItemListView: View {<br>    @StateObject var viewModel = ViewModel()<br>    var body: some View {<br>        NavigationStack {<br>            List {<br>                ForEach(viewModel.results, id: \.id) { item in<br>                    NavigationLink(destination: ItemDetailView(item: item)) {<br>                        VStack(alignment: .leading) {<br>                            Text(item.title ?? &quot;-&quot;).font(.title3)<br>                            Text(item.subtitle ?? &quot;-&quot;).font(.caption).foregroundColor(.secondary)<br>                        }<br>                    }<br>                }.onDelete(perform: viewModel.delete)<br>                Section {<br>                    Button {<br>                        viewModel.refreshItems()<br>                    } label: {<br>                        HStack {<br>                            Label(&quot;&quot;, systemImage: &quot;arrow.clockwise&quot;).labelStyle(.iconOnly)<br>                            Text(&quot;Refresh&quot;)<br>                        }<br>                    }.listRowBackground(Color.clear)<br>                        .buttonStyle(.borderedProminent)<br>                }<br>            }.onAppear {<br>                viewModel.loadItems()<br>            }.navigationTitle(&quot;Items&quot;)<br>                .toolbar {<br>                    #if os(iOS)<br>                        ToolbarItem(placement: .navigationBarTrailing) {<br>                            EditButton()<br>                        }<br>                    #endif<br>                    ToolbarItem {<br>                        Button(action: viewModel.toggleForm) {<br>                            Label(&quot;Add Item&quot;, systemImage: &quot;plus&quot;)<br>                        }<br>                    }<br>                }.sheet(isPresented: $viewModel.formVisible) {<br>                    NavigationStack {<br>                        Form {<br>                            TextField(&quot;Title&quot;, text: $viewModel.newItemTitle)<br>                            TextField(&quot;Subtitle&quot;, text: $viewModel.newItemSubtitle)<br>                        }.navigationTitle(&quot;New Item&quot;)<br>                            .toolbar {<br>                                ToolbarItem(placement: .cancellationAction) {<br>                                    Button {<br>                                        viewModel.formVisible = false<br>                                    } label: {<br>                                        Text(&quot;Cancel&quot;)<br>                                    }<br>                                }<br>                                ToolbarItem(placement: .confirmationAction) {<br>                                    Button {<br>                                        viewModel.createNewItem()<br>                                    } label: {<br>                                        Text(&quot;Save&quot;)<br>                                    }.disabled(!viewModel.formValid)<br>                                }<br>                            }<br>                    }<br>                }<br>        }<br>    }<br>}</pre><p>Now the view model:</p><pre>extension ItemListView {<br>    @MainActor class ViewModel: ObservableObject {<br>        private let coreDataManager = PersistenceController.shared<br>        private let repo = CoreDataRepository&lt;ItemEntity&gt;(context: PersistenceController.shared.container.viewContext)<br><br>        @AppStorage(&quot;initial-load&quot;) var initialLoad = true<br>        @Published var results: [ItemEntity] = []<br>        @Published var formVisible = false<br>        @Published var newItemTitle = &quot;&quot;<br>        @Published var newItemSubtitle = &quot;&quot;<br><br>        var formValid: Bool {<br>            !newItemTitle.isEmpty &amp;&amp; !newItemSubtitle.isEmpty<br>        }<br><br>        init() {<br>            getInitialData()<br>        }<br><br>        func toggleForm() {<br>            formVisible.toggle()<br>        }<br><br>        func loadItems() {<br>            do {<br>                results.removeAll()<br>                results = try repo.fetch().get()<br>            } catch {<br>                print(error)<br>            }<br>        }<br><br>        func createNewItem() {<br>            let result = repo.create { item in<br>                item.id = UUID()<br>                item.title = self.newItemTitle<br>                item.subtitle = self.newItemSubtitle<br>            }<br><br>            do {<br>                let newItem = try result.get()<br>                NetworkManager().post(&quot;/items&quot;, input: newItem, output: NetworkManager.ResponseMessage.self) { result in<br>                    do {<br>                        _ = try result.get()<br>                        self.formVisible = false<br>                        self.loadItems()<br>                    } catch {<br>                        print(error)<br>                    }<br>                }<br>            } catch {<br>                print(error)<br>            }<br>        }<br><br>        func refreshItems() {<br>            NetworkManager().get(&quot;/items&quot;, output: [ItemEntity].self) { result in<br>                do {<br>                    _ = try result.get()<br>                    try self.coreDataManager.saveContext()<br>                    self.initialLoad = false<br>                    self.loadItems()<br>                } catch {<br>                    print(error)<br>                }<br>            }<br>        }<br><br>        func delete(at offsets: IndexSet) {<br>            guard let index = offsets.first<br>            else { return }<br>            let el = results[index]<br>            let result = repo.delete(el)<br>            switch result {<br>            case .success:<br>                loadItems()<br>            case let .failure(error):<br>                print(error)<br>            }<br>        }<br><br>        private func getInitialData() {<br>            if !initialLoad { return }<br>            refreshItems()<br>        }<br>    }<br>}</pre><p>You may have noticed the CoreDataRepository . This quick helper provides methods for working with our CoreData entities.</p><pre>struct CoreDataRepository&lt;Entity: NSManagedObject&gt; {<br>    private let context: NSManagedObjectContext<br><br>    init(context: NSManagedObjectContext) {<br>        self.context = context<br>    }<br><br>    func fetch(sortDescriptors: [NSSortDescriptor] = [],<br>               predicate: NSPredicate? = nil) -&gt; Result&lt;[Entity], Error&gt;<br>    {<br>        let request = Entity.fetchRequest()<br>        request.sortDescriptors = sortDescriptors<br>        request.predicate = predicate<br><br>        do {<br>            let results = try context.fetch(request) as! [Entity]<br>            return .success(results)<br>        } catch {<br>            return .failure(error)<br>        }<br>    }<br><br>    func create(_ body: @escaping (inout Entity) -&gt; Void) -&gt; Result&lt;Entity, Error&gt; {<br>        var entity = Entity(context: context)<br>        body(&amp;entity)<br>        do {<br>            try context.save()<br>            return .success(entity)<br>        } catch {<br>            return .failure(error)<br>        }<br>    }<br><br>    func update(_ entity: Entity) -&gt; Result&lt;Entity, Error&gt; {<br>        do {<br>            try context.save()<br>            return .success(entity)<br>        } catch {<br>            return .failure(error)<br>        }<br>    }<br><br>    func delete(_ entity: Entity) -&gt; Result&lt;Void, Error&gt; {<br>        do {<br>            context.delete(entity)<br>            try context.save()<br>            return .success(())<br>        } catch {<br>            return .failure(error)<br>        }<br>    }<br><br>    enum Errors: Error {<br>        case objectNotFound<br>    }<br>}</pre><p>Now let&#39;s fire up our “remote” server. From the project root, navigate to the server directory, install dependencies, and start listening for requests.</p><pre>cd server/<br>npm install<br>node index.js</pre><p>You&#39;re ready to run the app and see our offline-first approach in action. From Xcode, run the app in your preferred iOS simulator. If all goes according to plan, you should see a screen like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zOVXBDMEcoBssvq_wwWFzA.png" /></figure><p>Play around creating entities and disabling the server to see the local-first data presented.</p><p>There you have it, folks! CoreData and remote data are now buds. Your users can use the app offline and sync when they return to the grid. Coffee’s ready without the grocery store trip! Cheers! 🎉</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f247b3ce6a27" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/decodable-coredata-a-proof-of-concept-for-building-offline-first-ios-apps-f247b3ce6a27">Decodable CoreData: A Proof-of-Concept for Building Offline-First iOS Apps</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Redux and the Chrome Storage API as a Single Source of Truth in Your Extensions]]></title>
            <link>https://medium.com/@drewalth/build-chrome-extensions-with-react-and-redux-using-the-stale-while-refresh-approach-b8c791ec9ca0?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8c791ec9ca0</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[chrome]]></category>
            <category><![CDATA[chrome-extension]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Sat, 01 Jul 2023 20:45:09 GMT</pubDate>
            <atom:updated>2023-07-03T19:39:30.396Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LiKOxsbu0cLxEITH" /><figcaption>Photo by <a href="https://unsplash.com/@fede_burgalassi?utm_source=medium&amp;utm_medium=referral">Federico Burgalassi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine embarking on a journey of crafting a Google Chrome extension, but this is no ordinary extension. It’s an application that harnesses the power of Redux, a predictable state container, to share data seamlessly between a background script and a UI app. But we don’t stop there. This extension is set to tap into a remote API to fetch data and utilize Chrome’s storage to persist the fetched data. Sound interesting? Let’s dive right in.</p><p>First, we scaffold the React app with Vite, a fast build tool for web apps. We also add TypeScript to the mix to ensure type safety. Next, we install the Redux library and its dependencies.</p><pre>npm create vite@latest chrome-extension -- --template react-ts<br>cd chrome-extension<br>npm install<br>npm install redux react-thunk</pre><p>We will also use the <a href="https://crxjs.dev/vite-plugin/">@crxjs/vite-plugin</a> Vite plugin to enable hot reloading for our Chrome extension.</p><pre>npm install @crxjs/vite-plugin@beta -D</pre><p>At the heart of our Chrome extension are several crucial files and folders. We begin by setting the foundation with a `manifest.json` file, which acts as a roadmap for our extension. Next, we establish a `background.ts` file for our service worker and point to the config for the popup (React app).</p><pre>{<br>  &quot;manifest_version&quot;: 3,<br>  &quot;name&quot;: &quot;My Redux Extension&quot;,<br>  &quot;version&quot;: &quot;1.0&quot;,<br>  &quot;description&quot;: &quot;Extension with Redux Store&quot;,<br>  &quot;permissions&quot;: [<br>    &quot;storage&quot;<br>  ],<br>  &quot;background&quot;: {<br>    &quot;service_worker&quot;: &quot;src/background.ts&quot;,<br>    &quot;type&quot;: &quot;module&quot;<br>  },<br>  &quot;action&quot;: {<br>    &quot;default_popup&quot;: &quot;index.html&quot;<br>  }<br>}</pre><p>Our `manifest.json` file serves as the blueprint of our extension. It lays out the specifications of our extension, such as defining the background script, default popup, and permissions needed for storage and accessing our API.</p><p>Now, let’s venture into the heart of our Redux integration — the `background.ts` file. Here, we set up our Redux store with an initial state and a reducer to manage our state transitions. Our store is armed with a message event listener, ready to handle data requests from the UI. Upon receiving a request, the store fetches data from Chrome storage if<br>available, immediately responding with the persisted data. But it doesn’t stop there. It simultaneously reaches out to the remote API for fresh data. This stale-while-revalidate strategy ensures that the extension provides<br>instant data while updating the information.</p><p>Our fancy new Chrome Extension will use the Pokémon API to fetch and present data about Ditto.</p><p>Let&#39;s set up the Redux store.</p><pre>import {createStore, applyMiddleware} from &quot;redux&quot;;<br>import thunk from &quot;redux-thunk&quot;;<br>import {State} from &quot;./types.ts&quot;;<br><br>const initialState: State = {<br>    data: null,<br>    isLoading: false,<br>    error: null,<br>};<br><br>const reducer = (state = initialState, action: any) =&gt; {<br>    switch (action.type) {<br>        case &quot;FETCH_DATA_BEGIN&quot;:<br>            return {...state, isLoading: true};<br>        case &quot;FETCH_DATA_SUCCESS&quot;:<br>            return {...state, isLoading: false, data: action.payload};<br>        case &quot;FETCH_DATA_ERROR&quot;:<br>            return {...state, isLoading: false, error: action.payload};<br>        default:<br>            return state;<br>    }<br>};<br><br>const store = createStore(reducer, applyMiddleware(thunk));</pre><p>Now let&#39;s write a function to fetch data from the API and persist it in Chrome storage.</p><pre>const fetchDataFromApi = () =&gt; async (dispatch) =&gt; {<br>    dispatch({type: &quot;FETCH_DATA_BEGIN&quot;});<br><br>    try {<br>        const response = await fetch(&quot;https://pokeapi.co/api/v2/pokemon/ditto&quot;);<br>        const data = await response.json();<br><br>        dispatch({type: &quot;FETCH_DATA_SUCCESS&quot;, payload: data});<br><br>        // Persist data in Chrome storage<br>        await chrome.storage.local.set({data});<br>    } catch (error) {<br>        dispatch({type: &quot;FETCH_DATA_ERROR&quot;, payload: error});<br>    }<br>};</pre><p>In the last step for the background script, we add a message event listener to handle data requests from the UI.</p><pre>chrome.runtime.onMessage.addListener((request, sender, sendResponse) =&gt; {<br>    if (request.action === &quot;FETCH_DATA&quot;) {<br>        // Fetch data from chrome storage if available<br>        chrome.storage.local.get([&quot;data&quot;], function (result) {<br>            // Send data to popup<br>            console.log(&quot;result.data: &quot;, result.data);<br>            sendResponse({data: result.data});<br><br>            // Then, fetch updated data from API<br>            store.dispatch(fetchDataFromApi());<br>        });<br>    }<br>    return true; // Will respond asynchronously.<br>});</pre><p>Next, we pivot to the src folder, creating a simple user interface for our extension in the App.tsxfile. To fetch and present data, we add logic to send a message to our background script whenever data is needed. The script responds promptly with the data for the UI to display.</p><pre>const [ditto, setDitto] = useState&lt;Ditto&gt;();<br><br>useEffect(() =&gt; {<br>    chrome.runtime.sendMessage({action: &quot;FETCH_DATA&quot;}, (response) =&gt; {<br>        setDitto(response.data);<br>    });<br>}, []);</pre><p>Now, in the project root run</p><pre>npm run dev</pre><p>Open the extensions manager, chrome://extensions/enable developer mode, click “load unpacked,” and select the chrome-extension-redux/dist/ directory. Pin the extension to your toolbar and open the popup. You should see some info about Ditto.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/648/1*1l5rXEbrwq5nV7pMaVkiBQ.png" /></figure><p>The culmination of this journey results in a Chrome extension that effectively combines Redux with the stale-while-refresh (SWR) strategy. This showcases how Redux can be utilized for developing a Chrome extension and illustrates the versatility of Redux and its capacity to manage shared state across different parts of an application, even in a Chrome extension.</p><p>And that’s it! As with all journeys, this is just the beginning. The next steps could include handling edge cases, testing, optimizing for performance, adding correct TS typing 😅, and more. I hope this article helps you plan your next Chrome extension project. Happy coding!</p><p>For the full project code, see <a href="https://github.com/drewalth/chrome-extension-redux">https://github.com/drewalth/chrome-extension-redux</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8c791ec9ca0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Few Code Examples for Reactjs Engineers Learning Swift and SwiftUI]]></title>
            <link>https://medium.com/better-programming/a-few-code-examples-for-reactjs-engineers-learning-swift-and-swiftui-c9bfd033ae6d?source=rss-f64f438fae9a------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9bfd033ae6d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[frontend-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Drew Althage]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 20:30:05 GMT</pubDate>
            <atom:updated>2023-07-03T20:19:12.115Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Cl-Xj1a5zJinOUGv" /><figcaption>Photo by <a href="https://unsplash.com/@vojtechbruzek?utm_source=medium&amp;utm_medium=referral">Vojtech Bruzek</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a software engineer familiar with ReactJS, learning Swift and SwiftUI can be a smooth transition if you can map the concepts you are familiar with to the new environment. In this guide, we will look at how common ReactJS patterns translate into Swift and SwiftUI.</p><p>Please note — There are a million different ways to skin a cat. The following examples are intended to be short code snippets to highlight general concepts.</p><p>I recommend <a href="https://github.com/drewalth/quick-swiftui-examples">downloading the Playground</a> from GitHub to experiment with and use these examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cu-8ALdxoAK7Ekes8Vb9sA.png" /></figure><h3>Initializing a Project</h3><p>There are many ways of starting a new React project; one method is using create-react-app:</p><pre>npx create-react-app my-app<br>cd my-app<br>npm start</pre><p>In Swift, you use Xcode to create a new SwiftUI project:</p><ol><li>Open Xcode</li><li>Select “Create a new Xcode project”</li><li>With iOS (or macOS or Multiplatform) selected, choose “App” and select SwiftUI for the “interface” option.</li></ol><h3>Structuring Components</h3><p>Components are the building blocks of your application’s UI.</p><p>In React, components are often functions that return some JSX.</p><pre>const Greeting = () =&gt; &lt;h1&gt;Hello, world!&lt;/h1&gt;;</pre><p>In SwiftUI, components are called Views. You define them as structures that conform to the View protocol.</p><pre>struct Greeting: View {<br>    var body: some View {<br>        Text(&quot;Hello, world!&quot;)<br>    }<br>}</pre><h3>Capturing Form Inputs</h3><p>Handling user inputs is a common pattern in any application.</p><h4>ReactJS:</h4><p>In React, you might create an input field and use the useState hook to keep track of its value.</p><pre>const InputComponent = () =&gt; {<br>  const [inputValue, setInputValue] = useState(&quot;&quot;);<br>  <br>  const handleChange = event =&gt; setInputValue(event.target.value);<br>  <br>  return &lt;input type=&quot;text&quot; value={inputValue} onChange={handleChange} /&gt;;<br>};</pre><h4>SwiftUI:</h4><p>SwiftUI streamlines this process. By using the @State property wrapper and binding it to an input, SwiftUI handles the synchronization for you.</p><pre>struct InputView: View {<br>    @State private var inputValue = &quot;&quot;<br>    <br>    var body: some View {<br>        TextField(&quot;Enter text&quot;, text: $inputValue)<br>            .padding()<br>    }<br>}</pre><h3>Using State</h3><p>State is essential for reactive user interfaces.</p><h4>ReactJS:</h4><p>In React, we often use the useState hook to manage component-level state.</p><pre>const Counter = () =&gt; {<br>  const [count, setCount] = useState(0);<br><br>  return (<br>    &lt;button onClick={() =&gt; setCount(count + 1)}&gt;<br>      Clicked {count} times<br>    &lt;/button&gt;<br>  );<br>};</pre><h4>SwiftUI:</h4><p>Similarly, in SwiftUI, we use the @State property wrapper to keep track of the local state in a view.</p><pre>struct CounterView: View {<br>    @State private var count = 0<br>    <br>    var body: some View {<br>        Button(&quot;Clicked \(count) times&quot;) {<br>            count += 1<br>        }<br>        .padding()<br>    }<br>}</pre><h3>Passing Callbacks to Child Components</h3><p>Passing functions as props is common for parent-child communication.</p><h4>ReactJS:</h4><p>In React, you can pass a function to a child component via props that the child can call.</p><pre>const Parent = () =&gt; {<br>  const handleAction = () =&gt; console.log(&quot;Action handled&quot;);<br>  <br>  return &lt;Child onAction={handleAction} /&gt;;<br>};<br><br>const Child = ({ onAction }) =&gt; &lt;button onClick={onAction}&gt;Do Action&lt;/button&gt;;</pre><h4>SwiftUI:</h4><p>The same can be achieved in SwiftUI by passing closures to child views.</p><pre>struct ParentView: View {<br>    var body: some View {<br>        ChildView(onAction: { print(&quot;Action handled&quot;) })<br>    }<br>}<br><br>struct ChildView: View {<br>    let onAction: () -&gt; Void<br>    <br>    var body: some View {<br>        Button(&quot;Do Action&quot;, action: onAction)<br>    }<br>}</pre><h3>Sharing Data Across the App</h3><p>Applications often require sharing data among various components.</p><h4>ReactJS (using Context):</h4><p>In React, the Context API is a popular choice for sharing state and passing it deep into the component tree without manually passing props.</p><pre>const AppContext = createContext();<br><br>const Parent = () =&gt; (<br>  &lt;AppContext.Provider value={{ message: &quot;Hello from context&quot; }}&gt;<br>    &lt;Child /&gt;<br>  &lt;/AppContext.Provider&gt;<br>);<br><br>const Child = () =&gt; {<br>  const context = useContext(AppContext);<br>  <br>  return &lt;div&gt;{context.message}&lt;/div&gt;;<br>};</pre><h4>SwiftUI (using EnvironmentObject):</h4><p>SwiftUI offers EnvironmentObject, allowing views to share a common data source.</p><pre>class AppData: ObservableObject {<br>    @Published var message = &quot;Hello from environment object&quot;<br>}<br><br>struct ParentView: View {<br>    var body: some View {<br>        ChildView().environmentObject(AppData())<br>    }<br>}<br><br>struct ChildView: View {<br>    @EnvironmentObject var appData: AppData<br>    <br>    var body: some View {<br>        Text(appData.message)<br>    }<br>}</pre><h3>Handling Side Effects</h3><p>Reacting to changes is crucial for any modern UI Framework.</p><h4>ReactJS (using useEffect):</h4><p>In React, the useEffect hook allows you to perform side effects in function components.</p><pre>const MyComponent = () =&gt; {<br>  useEffect(() =&gt; {<br>    console.log(&quot;Component mounted&quot;);<br>    <br>    return () =&gt; console.log(&quot;Component unmounted&quot;);<br>  }, []);<br>  <br>  return &lt;div&gt;Hello, World!&lt;/div&gt;;<br>};</pre><h4>SwiftUI (using onAppear and onDisappear):</h4><p>SwiftUI provides onAppear and onDisappear modifiers that can be attached to views for similar functionality.</p><pre>struct MyView: View {<br>    var body: some View {<br>        Text(&quot;Hello, World!&quot;)<br>            .onAppear {<br>                print(&quot;View appeared&quot;)<br>            }<br>            .onDisappear {<br>                print(&quot;View disappeared&quot;)<br>            }<br>    }<br>}</pre><p>Side note, using the .task modifier may be preferable to .onAppear for invoking async functions when a view first renders. If the view has been destroyed before the task completes, the task will automatically be canceled.</p><h3>Routing and Navigation</h3><p>Navigation is the backbone of any application.</p><h4>ReactJS (using React Router):</h4><p>In React, React Router is commonly used for navigation.</p><pre>import { BrowserRouter as Router, Route, Link } from &quot;react-router-dom&quot;;<br><br>const Navigation = () =&gt; (<br>  &lt;Router&gt;<br>    &lt;div&gt;<br>      &lt;nav&gt;<br>        &lt;ul&gt;<br>          &lt;li&gt;&lt;Link to=&quot;/&quot;&gt;Home&lt;/Link&gt;&lt;/li&gt;<br>        &lt;/ul&gt;<br>      &lt;/nav&gt;<br>      <br>      &lt;Route path=&quot;/&quot; exact component={Home} /&gt;<br>    &lt;/div&gt;<br>  &lt;/Router&gt;<br>);</pre><h4>SwiftUI (using NavigationView and NavigationLink):</h4><p>SwiftUI provides NavigationView and NavigationLink for creating navigational interfaces.</p><pre>struct NavigationExampleView: View {<br>    var body: some View {<br>        NavigationView {<br>            NavigationLink(destination: HomeView()) {<br>                Text(&quot;Home&quot;)<br>            }<br>        }<br>    }<br>}</pre><h3>Conclusion</h3><p>SwiftUI brings a declarative way of building UI similar to ReactJS but more tightly integrated with Swift.</p><p>Understanding these mappings between ReactJS and SwiftUI can make transitioning between the two more intuitive. While a learning curve is involved, understanding the similarities and differences in patterns can make the process smoother.</p><p>Remember that SwiftUI is evolving rapidly, so stay updated with the latest changes and features.</p><p>When you’re ready to move onto HTTP requests and hook up your app to a remote API, check out “<a href="https://medium.com/better-programming/simple-network-layer-for-js-developers-learning-swift-b93bc4eab46b">Transitioning From JavaScript to Swift and SwiftUI? Start With This Simple Networking Layer</a>”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9bfd033ae6d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/a-few-code-examples-for-reactjs-engineers-learning-swift-and-swiftui-c9bfd033ae6d">A Few Code Examples for Reactjs Engineers Learning Swift and SwiftUI</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>