<?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 Hyun Lee (Mia) on Medium]]></title>
        <description><![CDATA[Stories by Hyun Lee (Mia) on Medium]]></description>
        <link>https://medium.com/@hyunleemia?source=rss-19b58353dd92------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*93ty01xZS9XQzj78SJBEAg.png</url>
            <title>Stories by Hyun Lee (Mia) on Medium</title>
            <link>https://medium.com/@hyunleemia?source=rss-19b58353dd92------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:56:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hyunleemia/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[How to utilise MusicKit for iOS development]]></title>
            <link>https://hyunleemia.medium.com/utilising-musickit-for-ios-development-0dbb74f6b6b0?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/0dbb74f6b6b0</guid>
            <category><![CDATA[musickit]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[apple-music]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Sun, 04 Aug 2024 12:50:54 GMT</pubDate>
            <atom:updated>2024-08-05T01:50:54.964Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yBeFuT00cEZeUP1e.jpg" /></figure><p>Using MusicKit is a great way to bring music to iOS apps. Thanks to its close integration with the Apple ecosystem, it is easier to access Apple’s music catalog through MusicKit than through external APIs.</p><p><strong>Quick access to what you might need:</strong></p><ol><li><a href="#489a">Registering to use MusicKit in your iOS app</a></li><li><a href="#6c9c">Getting user’s permission</a></li><li><a href="#8e93">Checking user’s subscription status</a></li><li><a href="#6356">Searching for music using text search</a></li><li><a href="#c603">Searching for music using ISRC (international standard record code)</a></li><li><a href="#9845">Getting Apple Music’s recommendations for user</a></li><li><a href="#cd6f">Getting track music items from albums and playlists</a></li></ol><h3>First, let’s clear the confusion</h3><p>While I was going through resources to refer to when integrating MusicKit into my iOS app, I was confused about the requirements.</p><p>There was a lot of Apple Music API and outdated MusicKit resources which stated that developer tokens need to be generated to retrieve data from MusicKit.</p><p>After more research, I figured that for native iOS apps to use MusicKit, developer tokens are not required. For web apps or other mobile development environments, developers can use Apple Music API to retrieve the necessary information.</p><p>However, it is important to note that to utilise MusicKit, you need to be part of the Apple Developer Program. Else, I believe that the best next step is to use the Apple Music API which is a lot more complicated to set up.</p><p>Now that this is out of the way, let’s dive into how we can easily integrate MusicKit to our iOS apps.</p><h3>Set up to use MusicKit</h3><h4>1. Register to use MusicKit</h4><p>To use MusicKit, you need to first enable this service on your <a href="https://developer.apple.com/account">Apple Developer Account</a>.</p><p>Create an identifier for your app (if you haven’t yet). This can be done in your <a href="https://developer.apple.com/account/resources/identifiers/list">Apple Developer Account page under identifiers</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtwjCPg6XUqP3K2jkpq_Mg.png" /></figure><p>Under the identifier page of your app, go to App Services and enable MusicKit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EIxxNBKbVvQePlW1BxfcCg.png" /></figure><p>Now you are registered and authorized to access MusicKit from your app.</p><h4>2. Getting user’s permission</h4><p>Now that you have been provisioned to use MusicKit from Apple. You need to get the user’s permission to access their media library (music library).</p><p>In order to do that, you need to set up the capability in Xcode’s info.plist:</p><p>Add the “Privacy — Media Library Usage Description” key in the Custom iOS Target Properties section. Don’t forget to state the reason for requiring this permission.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8UCs_qc91gE_IhHX8yEmw.png" /></figure><p>To initiate the pop up that requests for permission and handles the response, you can use the following code:</p><pre>private func requestMusicAuthorization() async {<br>    let status = await MusicAuthorization.request()<br>    <br>    switch status{<br>    case .authorized:<br>        isMusicAuthorized = true<br>    case .notDetermined:<br>        print(&quot;Error getting Apple Music Authorization: Not determined&quot;)<br>    case .restricted:<br>        print(&quot;Error getting Apple Music Authorization: Restricted&quot;)<br>    case .denied:<br>        print(&quot;Error getting Apple Music Authorization: Denied&quot;)<br>    default:<br>        print(&quot;Error getting Apple Music Authorization: Unknown (New case)&quot;)<br>    }<br>}</pre><p>You can call this function in the view where you want users to see the popup requesting for permission. You can also handle different status in different ways depending on how you want to design your flow.</p><h4>3. Checking the user’s subscription data</h4><p>With a simple integration to MusicKit, you can access their catalogs. To go further, if the user has a subscription to Apple Music, you can also access the library of the user and initiate music playback within your own app.</p><p>You want to only show these features to the user if they are a subscriber so it is important to check if the user’s subscription status.</p><pre>private func checkMusicSubscription() async{<br>    for await subscription in MusicSubscription.subscriptionUpdates{<br>        musicSubscription = subscription<br>        DispatchQueue.main.async{<br>            self.canPlayAppleMusic = self.musicSubscription?.canPlayCatalogContent ?? false<br>        }<br>    }<br>}</pre><p>As shown above, you can check if the user is able to play the catalog content, which in turn shows if they are a subscriber.</p><p>For my implementation, I realised that the subscriptionUpdates do not return, meaning that it continues to wait for the subscription updates to come in. While this is useful if you want to constantly check to ensure that related features are not shown to unsubscribing users, for my use case, I wanted to run more tasks after the subscription status was checked.</p><p>So I used a workaround to force an exit.</p><pre>func checkAuthAndSubscription() async{<br>    let timeout = 2.0<br>    let startTime = Date()<br>    <br>    await requestMusicAuthorization()<br>    let subscriptionTask = Task {<br>        await checkMusicSubscription()<br>    }<br>    <br>    try? await withThrowingTaskGroup(of: Void.self){ group in<br>        group.addTask{<br>            try await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))<br>            if !subscriptionTask.isCancelled{<br>                print(&quot;Timeout&quot;)<br>                subscriptionTask.cancel()<br>            }<br>        }<br>        <br>        group.addTask{<br>            await subscriptionTask.value<br>        }<br>        <br>        try await group.next()<br>        group.cancelAll()<br>    }<br>}</pre><h3>Use MusicKit</h3><p>Now that the set up is done, we can start using features powered by MusicKit.</p><h4>4. Searching for music using text search</h4><p>Similar to how we can search for music using keywords in the Apple Music App, we can utilise the same functionality in our own iOS app.</p><pre>private func searchForMusicItems() async{<br>    var request = MusicCatalogSearchRequest(term: searchTerm, types: [Song.self])<br>    request.limit = 10<br>    do{<br>        let response = try await request.response()<br>        musicSearchResults = response.songs<br>    }catch{<br>        print(&quot;Error in requesting for search: \(error)&quot;)<br>    }<br>}</pre><p>We create request object and await its response asynchronously.</p><p>If you want to search for a playlist or album, you can add that in the array of the types parameter.</p><h4>5. Searching for music using ISRC (international standard record code)</h4><p>ISRC is an internationally recognised unique code for recordings. It is particularly useful in searching for a specific song. Searching by unique ISRC requires a MusicCatalogResourceRequest unlike searching by keyword which requires a MusicCatalogSearchRequest. If we try to search by ISRC in using MusicCatalogSearchRequest it will not return accurate results.</p><pre>private func isrcToSong(isrc: String) async -&gt; Song?{<br>    var request = MusicCatalogResourceRequest&lt;Song&gt;(matching: \.isrc, equalTo: isrc)<br>    <br>    do {<br>        let response = try await request.response()<br>        <br>        print(response)<br>        <br>        guard let musicItem = response.items.first else {<br>            print(&quot;No music item found for ISRC: \(isrc)&quot;)<br>            return nil<br>        }<br>        return musicItem<br>    } catch {<br>        print(&quot;Error fetching music by ISRC: \(error)&quot;)<br>        return nil<br>    }<br>}</pre><h4>6. Getting Apple Music’s recommendations for user</h4><p>MusicKit also allows us to get other interesting music items for subscribing users. An example is Apple Music recommendations. This is a suggested list of albums, tracks, playlists and stations based on the user’s activity on Apple Music.</p><p>This is great because we are unable to get any specific user activity data from MusicKit. Recommendations from MusicKit means that developers don’t need user activity data or a machine learning model to generate recommendations on their apps.</p><pre>private func getRecommendationsFromApple() async{<br>    let request = MusicPersonalRecommendationsRequest()<br>    do{<br>        let response = try await request.response()<br>        musicPersonalRecommendations = response.recommendations<br>    }catch{<br>        print(&quot;Error in requesting for recommendations: \(error)&quot;)<br>    }<br>}</pre><h4>7. Getting track music items from albums and playlists</h4><p>Assuming we received album and playlist recommendations and would like to get the track items from them, you can do so through the code below.</p><pre>private func extractRecommendationMusicISRC() async -&gt;  [String] {<br>    guard let appleMusicRecommendations = musicPersonalRecommendations else {<br>        print(&quot;No Apple Music recommendations returned&quot;)<br>        return []<br>    }<br>    var trackISRC: [String] = []<br>    for theme in appleMusicRecommendations{<br>        let item = theme.items[0]<br>        switch item{<br>        case .album(let album):<br>            do{<br>                if let tracks = try await album.with([.tracks]).tracks{<br>                    for track in tracks{<br>                        if let isrc = track.isrc{<br>                            trackISRC.append(isrc)<br>                        }<br>                    }<br>                }<br>            }catch{<br>                print(&quot;Error in getting tracks from album: \(error)&quot;)<br>            }<br>        case .playlist(let playlist):<br>            do{<br>                if let tracks = try await playlist.with([.tracks]).tracks{<br>                    for track in tracks{<br>                        if let isrc = track.isrc{<br>                            trackISRC.append(isrc)<br>                        }<br>                    }<br>                }<br>            }catch{<br>                print(&quot;Error in getting tracks from playlist: \(error)&quot;)<br>            }<br>        case .station(_):<br>            continue<br>        @unknown default:<br>            continue<br>        }<br>    }<br>    return trackISRC<br>}</pre><h3>Conclusion</h3><p>All in all, MusicKit is really fun to use and it has a variety of datapoints that we can reach into to create exciting features, you just need to know how to use them!</p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0dbb74f6b6b0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fixing diffable data source error in UICalendarView]]></title>
            <link>https://hyunleemia.medium.com/fixing-diffable-data-source-error-in-uicalendarview-439a5152d709?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/439a5152d709</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[diffable-data-sources]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[delegate]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Sat, 20 Jul 2024 06:26:26 GMT</pubDate>
            <atom:updated>2024-07-20T06:31:29.250Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TLDR: How I resolved a diffable data source error for UICalendarView when user tries to access dates in the far past and future. SwiftUI + UICalendarView (iOS 17.5)</blockquote><h3>The app</h3><p>Rapha is an app that allows users to manage their chronic illness by recording their pain, medication and lab results.</p><p>The main (home) view contains a calendar and a list view of the main category of items. Users can view their records at a glance on the calendar and create new records by choosing a data and clicking the category of record that they want to add.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZtXOjHvnm292BHv7LFgoeA.png" /></figure><h3>The bug</h3><p>Assuming today is the 20th July 2024, if the user was to go quite far back in time on the calendar (i.e. 1st January 2020), and selected a category to draft a records, the app would crash.</p><p>This was a really bad bug because even after force restarting, the app does not work and the only way to resolve this is to delete the app and re-download. Deleting the app would mean losing all the locally persisted data — meaning all medical records would be gone with no backup.</p><p>These were the error messages I received upon crash, which at a glance, was not easy to decipher at all.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ml_BEch9Oqnn1KdcRCWeQ.png" /><figcaption>Error: Attempted to reconfigure item identifier that does not exist in the snapshot, &lt;_UIDatePickerCalendarDay…”</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LhRwvd7ywYh2UdlUgqV6hQ.png" /><figcaption>Error: Assertion failure in -[__UIDiffableDataSourceSnapshot _validateReloadUpdateThrowingIfNeeded:]…</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJfRAgE5zKgueO9nXpkcEg.png" /><figcaption>Error: Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Attempted to reconfigure item identifier that does not exist in the snapshot: &lt;UIDatePickerCalendarDay:…</figcaption></figure><h3>The fix</h3><p>Eventually (after a lot of research, trial and error) I managed to figure out where exactly the issue was happening and how to fix it.</p><p>The point at which this error occurs is when the UICalendarView tries to update the calendar and reload the decorations.</p><p>This was my original code (note that the function was a delegate function, meaning that it was declared by UICalendarView but the function is defined by the delegate).</p><pre>func updateUIView(_ uiView: UICalendarView, context: Context) {<br>    uiView.reloadInputViews()<br>    uiView.invalidateIntrinsicContentSize()<br>    uiView.reloadDecorations(forDateComponents: recordCopyClass.allRecords.map{Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: $0.date)}, animated: true)<br>}</pre><p>Previously, I reloaded the decorations for all dates that existed in the database of records uploaded by the user.</p><p>I’m still not 100% sure why this caused an error when I tried to reload the decorations for dates far back in the past. But my guess is that the UICalendarView only reloads the decoration for only some months in the past from the month that the user is being shown. So when provided with data from the distant future, it is unable to identify it and hence throws an error about an inconsistent data source.</p><p>Here is how I fixed the code.</p><pre>func updateUIView(_ uiView: UICalendarView, context: Context) {<br>    uiView.reloadInputViews()<br>    uiView.invalidateIntrinsicContentSize()<br>    var currentMonth = Calendar.current.component(.month, from: selectedDate)<br>    var forThisMonth = recordCopyClass.allRecords.map{Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: $0.date)}.filter{$0.year == currentYear &amp;&amp; $0.month == currentMonth}<br>    <br>    if !forThisMonth.isEmpty{<br>        uiView.reloadDecorations(forDateComponents: forThisMonth, animated: true)<br>    }<br>}</pre><p>I filtered the records’ dates based on whether they were in the same month as the month the user was looking at in the view. If there were no dates, there was no reason to update the calendar with decorations.</p><p>On the other hand, if there were indeed dates, I made it such that the UICalendarView would only have to render the decorations for the dates that exist within the month being viewed.</p><p>Once I made these changes, the app now worked well as intended even if I tried to view and create records for 20 years in the past. (Yay! 🎉)</p><h3>How I figured it out</h3><p>At first glance, XCode’s error flagging seemed cryptic — the console error referred to components I didn’t directly use, and the location where XCode flagged to be the point of error was a list of memory addresses.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ml_BEch9Oqnn1KdcRCWeQ.png" /><figcaption>Error: Attempted to reconfigure item identifier that does not exist in the snapshot, &lt;_UIDatePickerCalendarDay…”</figcaption></figure><p>By reading the console error and doing some Googling, I pieced together my first clue which was that this was related to a diffable data source that the UICalendarView was referencing from. Additionally, it seemed that the specific data the UICalendarView was missing was the correct date.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJfRAgE5zKgueO9nXpkcEg.png" /><figcaption>Error: Terminating app due to uncaught exception ‘NSInternalInconsistencyException’, reason: ‘Attempted to reconfigure item identifier that does not exist in the snapshot: &lt;UIDatePickerCalendarDay:…</figcaption></figure><p>I looked into the callstack and was able to get a clearer view on where exactly in my code the crash happened.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*90jahjVMlNLi_K7L8YQulw.png" /></figure><p>Working backwards from where the error erupted (0__pthread_kill ), I identified that the issue stemmed from the part where the UICalendarView was being reloaded new decorations from an array of DateComponents .</p><p>With the earlier guess that the error had something to do with the dates, I decided to filter the dates to only update the UICalendarView with the month that the user wanted to view.</p><p>Luckily, this resolved the issue and the app worked smoothly in viewing and creating records many months into the past.</p><h3>Signing off…</h3><p>If you’d like to take a deeper look at the code, you can do so on my <a href="https://github.com/acciohyun/Rapha">Github page here!</a> The corresponding code is in CalendarView.swift.</p><p>If you want to check out the free app on the App Store, <a href="https://apps.apple.com/kr/app/rapha-for-as/id6499498701?l=en-GBhttps://apps.apple.com/kr/app/rapha-for-as/id6499498701?l=en-GB">here it is</a>!</p><p>Thanks, and have a great day :-)</p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=439a5152d709" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Swift concurrency from DispatchQueue to Async/Await]]></title>
            <link>https://hyunleemia.medium.com/refactoring-swift-concurrency-from-dispatchqueue-to-async-await-edbd8c0945d9?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/edbd8c0945d9</guid>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Fri, 28 Jun 2024 03:04:04 GMT</pubDate>
            <atom:updated>2024-06-29T02:44:12.704Z</atom:updated>
            <content:encoded><![CDATA[<p>Handling concurrency can be a challenge for developers because writing asynchronous code is not as straightforward as writing sequential code. With Swift 5.5, an easier and higher level way of handling concurrency was introduced. This is mainly supported by the keywords async, await. Pre-existing methods include utilising DispatchQueue or escaping closures.</p><blockquote>In this article, I will share how to refactor concurrency code built with DispatchQueue to Async/Await instead. On the way, I will point out the use cases in which Async/Await is advantageous over DispatchQueue.</blockquote><p>Before diving into the code, let’s cover conceptual clarifications for anyone who might be new to this topic.</p><h3>Concurrency in Swift… A quick overview</h3><p><strong>GCD (Grand Central Dispatch)</strong></p><ul><li>According to Apple documentation, it is a central control that “allows us to execute [tasks] concurrently by submitting to dispatch queues”. This roughly means that it controls access to multiple threads.</li><li><em>Analogy</em>: It is like a train station with multiple tracks</li></ul><p><strong>Dispatch Queue</strong></p><ul><li>As a concept, it refers to queues where tasks are assigned and executed in a FIFO manner.</li><li>A DispatchQueue “object manages the execution of tasks serially or concurrently on the app’s main thread or background thread”, it manages the tasks based on the priority of the tasks (quality of service).</li><li><em>Analogy</em>: The DispatchQueue object acts like a station master that allocates different trains on different tracks based on their priority.</li></ul><p><strong>Async/Await</strong></p><ul><li>They are keywords that help make concurrency implementation easier for developers.</li><li>async keyword is added to functions that are to be processed asynchronously.</li><li>await keyword is added to moments in the code where an async action is called, pausing the code until the action is completed.</li></ul><p><strong>Actors</strong></p><ul><li>Actors are like classes implemented with concurrency safety in mind to ensure that no two pieces of code attempt to access on actor’s data at the same time.</li><li>They only allow access to a property when the object is available (when no other code is accessing and editing the property).</li></ul><h3>Refactoring — DispatchQueue to Async/Await</h3><p>While refactoring code for one of my SwiftUI apps that mostly used DispatchQueue to implement concurrency, I came across two examples highlighting how to implement async, await.</p><h4>Async functions can only be called within async functions or in a Task</h4><p>Below is the original code utilising DispatchQueue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TojBRNTX8bfAUY-8hkALew.png" /><figcaption>Definition of function: takePhoto()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yKJWP1JMP8uqs59JrvFoSg.png" /><figcaption>Usage of takePhoto() in view</figcaption></figure><p>This is the new code after replacing with async, await.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwU1mLGq83p9YjpUPjPFHw.png" /><figcaption>New definition of function: takePhoto()</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJD8bT0OBc0znvj_dXVT9g.png" /><figcaption>Usage of newly defined takePhoto() function</figcaption></figure><p>The keyword async was attached to the function takePhoto() to show that code within this function should happen asynchronously.</p><p>When used in the view code, it needs to be wrapped inside a Task. The await keyword marks the point where the code will stop while the asynchronous code is running. The action of the Button is not asynchronous by default, and we cannot call an asynchronous function in a synchronous function. Hence, we wrap the code in a Task. This means that the code inside the Task will run asynchronously, on a separate thread, allowing the program to execute other code that is not dependent on this function.</p><h4>Updating UI (/running tasks on main thread) from within an async task</h4><p>UI updates and changes have to happen on the main thread.</p><p>Sometimes, we want to be able to update the UI from within an async function. An example is receiving data via networking and updating the screen with the received data.</p><p>Previously, I used DispatchQueue.main.async to update the UI within asynchronous code in DispatchQueue.global.(qos: .background).async to do so. (As seen below)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E-t7azLhBk4kzPazOtOhBA.png" /><figcaption>Definition of photoOutput() using DispatchQueue</figcaption></figure><p>After refactoring to implement concurrency with async, await, the following code was created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VPLI1hvJ4RWyuPsaHfxQEw.png" /><figcaption>New definition of photoOutput() using Async/Await</figcaption></figure><p>The time-consuming code was wrapped in a Task, meaning that all code inside the Task will be handled asynchronously. However, within the Task, we need update the screen view after processing the image. An UI updates should only be done on the main thread.</p><p>If we want to update the UI using the processed image, we can utilise a @MainActor. This is because code within an @MainActor function runs on the main thread and we should update the UI through the main thread rather than any other background threads. Hence, I created a @MainActor function that contains all the action that should happen on the main thread, and added that into the Task after the image was processed asynchronously.</p><h3>Pros, Cons and when to use Async/Await</h3><p>For this app, I used concurrency for relatively straightforward tasks with low risk of a data race. While I believe that the benefits of using Async/Await, Tasks and Actors will be much more obvious when data is being edited asynchronously from various points, here are a few benefits I’ve noticed when implementing Async/Await in this use case.</p><ol><li>With Async/Await, developers don’t have to specify a qos. <br>A qos (quality of service) is a prioritisation of the task that is to be run asynchronously, it helps the GCD decide how to prioritise the task and hence decide the queue and thread it will be placed in. This is both a pro and a con, depending on the use case. <br>In my use case above, using Async/Await is much more convenient because of this reason. As it is not a very complicated use case, I don’t need to specify the priority, I can let the GCD handle the task appropriately. <br>On the other hand, in a situation where there are many different tasks happening asynchronously, developers may want to specify the priority for more control over how concurrency is being implemented in their app.</li><li>With Async/Await, there is clearer syntax.<br>The keywords async and await are very clear in defining which functions will be run asynchronously and where the developers will see a pause in execution. Concurrency is hard to debug because sometimes it is difficult to understand when the async code is running and what happens after that. The keywords are landmarks for debugging when developers try to understand how to fix unexpected behaviours in async code.</li></ol><h3>Conclusion</h3><p>Async/Await, Tasks and Actors has made it really convenient for developers to create and run concurrency. While there may be more complicated use cases that warrants the use of DispatchQueue and escaping closures, it’s good to know that there’s an additional option to use a higher level method of implementation.</p><h3>Resources</h3><p>Here are some resources that I referred to while implementing async/await:</p><ol><li><a href="https://github.com/swiftlang/swift-evolution/blob/main/proposals/0296-async-await.md">Swift evolution proposal for async/await </a><br>This Github page shows the accepted proposal for adding the async/await, personally found it a great resource in understanding the intention and background for implementing async/await.</li><li><a href="https://onnerb.medium.com/swift-concurrency-fd42c072234e">Swift concurrency </a>(Medium)<br>A concise introduction to async/await, Task and Actors.</li><li><a href="https://www.hackingwithswift.com/quick-start/concurrency">Swift concurrency</a> (Hacking with Swift)<br>More about async/await, Task and Actors with examples and other considerations (such as concurrency for sequential tasks)</li></ol><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edbd8c0945d9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using enums to store app content]]></title>
            <link>https://hyunleemia.medium.com/using-enums-to-store-app-content-53a2d89184e0?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/53a2d89184e0</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[enum]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[maintainability]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Wed, 26 Jun 2024 02:41:36 GMT</pubDate>
            <atom:updated>2024-06-26T03:43:47.514Z</atom:updated>
            <content:encoded><![CDATA[<p>At times, developers have to create and manage app content that users cannot change. Considering that the users’ interactions are restricted to read-only, it can be managed differently from data models intended for user CRUD. In fact, using data models to manage read-only data can be inefficient and error-prone, suggesting the opportunity for a better way to manage this data — enums .</p><blockquote>This article delves into how an enum was used to store app content and compares its benefits with the previous implementation (using a custom struct data model).</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tq_P4SrhnaT_9Uxab-KeQ.jpeg" /><figcaption>Screenshot of app implementation</figcaption></figure><h3>Understanding enums</h3><h4>What are enums? And what can we do with them?</h4><p>An enum is a data type that has a fixed set of values. Raw values of any data type can be assigned to these enum values (But the enum values have to be of the same data type). Computed properties can also be declared in enums, associating the fixed set of values a custom computation for other use cases. Enum values can also be iterated.</p><h4>When should we use enums to store app information/data?</h4><p>Enums should be used to represent data when said data can be pre-determined before runtime. Upon declaration, enums are expected to have a fixed set of values. Hence, the use case should be when data is not expected to be updated during runtime.</p><h3>Diving into the use case</h3><h4>Aim</h4><p>The aim was to create a questionnaire that would be pre-defined before the app is launched. The questions were immutable and was determined by the app’s use case (aka users cannot change the questions).</p><p>The questions had to have a question number (functioning as an ID to associate the user’s response to the question), the main question and the sub-question.</p><h4>Initial implementation</h4><p>Initially I defined the question in a custom struct data model (based on my previous experience of creating and storing user’s data in such models).</p><p>I defined a struct,</p><pre>struct IndivQnsBASDAI: Identifiable, Hashable{<br>    var id: Int<br>    var mainQns: String<br>    var subQns: String<br>    <br>    init(qnsNum: Int, mainQns: String, subQns: String){<br>        self.id = qnsNum<br>        self.mainQns = mainQns<br>        self.subQns = subQns<br>    }<br>    <br>}</pre><p>And then instantiated the struct for each question and placed them in an array.</p><pre>let qnsCollection = [IndivQnsBASDAI(qnsNum: 0, mainQns: &quot;Level of fatigue&quot;, subQns: &quot;Tiredness&quot;),<br>                         IndivQnsBASDAI(qnsNum: 1, mainQns: &quot;Level of AS pain&quot;, subQns: &quot;AS neck, back, or hip pain&quot;),<br>                         IndivQnsBASDAI(qnsNum: 2, mainQns: &quot;Other level of pain/swelling&quot;, subQns: &quot;In joints other than neck, back, and hips&quot;),<br>                         IndivQnsBASDAI(qnsNum: 3, mainQns: &quot;Level of discomfort&quot;, subQns: &quot;Discomfort from area tender to touch&quot;),<br>                         IndivQnsBASDAI(qnsNum: 4, mainQns: &quot;Level of morning stiffness&quot;, subQns: &quot;From the time you wake up&quot;),<br>                         IndivQnsBASDAI(qnsNum: 5, mainQns: &quot;Duration of morning stiffness&quot;, subQns: &quot;5 is one hour, 10 is two or more hours&quot;)]</pre><h4>The new approach using enums</h4><p>After going through a code review and being suggested to use enums instead, here is how I updated the code to reduce potential human errors and improve ease of maintenance.</p><pre>enum IndivQnsBASDAIEnum: Int, CaseIterable {<br>    case q1 = 0<br>    case q2<br>    case q3<br>    case q4<br>    case q5<br>    case q6<br>    <br>    var mainQns: String {<br>        switch self{<br>        case .q1:<br>            &quot;Level of fatigue&quot;<br>        case .q2:<br>            &quot;Level of AS pain&quot;<br>        case .q3:<br>            &quot;Other level of pain/swelling&quot;<br>        case .q4:<br>            &quot;Level of discomfort&quot;<br>        case .q5:<br>            &quot;Level of morning stiffness&quot;<br>        case .q6:<br>            &quot;Duration of morning stiffness&quot;<br>        }<br>    }<br>    <br>    var subQns: String {<br>        switch self{<br>        case .q1:<br>            &quot;Tiredness&quot;<br>        case .q2:<br>            &quot;AS neck, back, or hip pain&quot;<br>        case .q3:<br>            &quot;In joints other than neck, back, and hips&quot;<br>        case .q4:<br>            &quot;Discomfort from area tender to touch&quot;<br>        case .q5:<br>            &quot;From the time you wake up&quot;<br>        case .q6:<br>            &quot;5 is one hour, 10 is two or more hours&quot;<br>        }<br>    }<br>}</pre><p>Here’s what changed:</p><ol><li>An enum with the exhaustive cases of 6 questions was defined (each was assigned to a raw integer value starting from 0 — to be used in retrieving the corresponding response)</li><li>Computed properties mainQns and subQns were created to return the associated questions for each case of questions</li></ol><h4>How is this better?</h4><p>At a glance the updated implementation is lengthier but I personally feel that the benefits it brings is worth the longer code:</p><ol><li>Enums (in this case), reduce the possibility of human error. <br>Previously, if I wanted to reach into the main question of question 4, I had to use the index value to access the corresponding data. <br>mainQns = qnsCollection[3].mainQns<br>This is not only error prone but it reduces readability because then anyone else who reads this line of code will not be able to understand what data I am trying to retrieve here.<br>On the other hand, by using enums, it is not only more obvious but also the auto-completion on XCode gives us the confidence that the value exists and that we are reaching into the correct data. <br>mainQns = IndivQnsBASDAIEnum.q4.mainQns</li><li>Enums are easier to maintain in the long run. If we want to make changes to the data in the future, it is easier to do so. For example, if we decide that each question will now have an associated icon, we can simply add a computed property that returns the corresponding enum. However, in the case of using a struct and array, we not only have to edit the struct, its initialisers but also the array of questions. Personally, I think this takes more work hopping around different files implementing these changes.</li></ol><h3>Conclusion</h3><p>All in all, enums are a great way to store exhaustive cases. In this article I’ve shared one example of how I used enums to refactor my code to become a bit more readable and maintainable. I will share on other interesting code refactoring choices I’ve made and feel free to share yours too!</p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53a2d89184e0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My review of 100 Days of Swift (UIKit)]]></title>
            <link>https://hyunleemia.medium.com/my-review-of-100-days-of-swift-uikit-f1e4d2d3ee48?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/f1e4d2d3ee48</guid>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Thu, 16 May 2024 03:30:24 GMT</pubDate>
            <atom:updated>2024-05-18T08:28:31.248Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a review of “100 Days of Swift” which is a free course by Hacking with Swift.</p><blockquote>TLDR; “100 Days of Swift” is a great resource to start building apps from the basics and get into more complex ideas. It’ll probably be most effective only if it is attempted consistently and with more practice.</blockquote><h3>My initial concerns</h3><p>Before I started 100 Days of Swift, I had to decide if it was worth committing to the 100 days. I wasn’t sure if this course would help me grow in the way I wanted to and if it didn’t, I wanted to spend time on other resources that would.</p><p>I (thought) I knew the Swift syntax relatively well and at that point had some experience creating small simple apps through other tutorials online.</p><p>Here were my goals when I started “100 Days of Swift”:</p><ol><li>Write better Swift code. (i.e. code that follows best practices!)</li><li>More guidance on practicing more advanced Swift code.</li></ol><h3>My experience</h3><p>So after about 42 days of following 100 Days of Swift, here’s my take on the course.</p><ol><li>Builds a strong foundation <br>The first 15 days of course starts out with the basic Swift language. As mentioned, I had a basic understanding of these concepts. Regardless, I think I made a good decision going through these resources. Not only are basic concepts are covered here, the course also covers how to properly use them and different use cases. Personally, this revision was helpful in building a stronger foundation.</li><li>Paced learning <br>After the 15 days of basic concepts, the course progresses in projects. As we build small apps, different components and kits are introduced. It’s a good way to become very familiar with commonly used components and kits. By Project 10 (i.e. Day 42), I can confidently create table views, alerts and buttons without checking documentation, both programmatically and through the storyboard.</li><li>Need for consistency<br>Each day of this course takes less than 1 hour and once you get into the projects, the process is less of “studying” but more of “trying and getting experience”. To truly understand these concepts (i.e. how to set up alerts, how to properly use closures), consistency is very important in reinforcing the knowledge.</li><li>Advanced Swift <br>“100 Days of Swift” provides exposure and practice through projects and as the weeks progress, we not only get to try building with different UIKits but we also get exposure to more advanced Swift topics such as delegates and concurrency.</li></ol><p>All in all, “100 Days of Swift” is a good motivation provider to consistently code a little everyday, become very familiar with common components and kits, and learn about more difficult topics as they surface.</p><p>Some advice</p><p>If you’re thinking of starting “100 Days of Swift”, only attempt this if you can be consistent. 1 hour a day is not a long time, which means its easy to forget concepts that you learned just today. By consistently coming back to it everyday, the concepts stick better and longer.</p><p>One other thing that helped was that once you feel more confident, try to code the projects before the code is revealed. While it will definitely take a lot of time and the code will not be great, I definitely think I apply the concepts into code better when I attempt it first and experience firsthand, the issues that arise during implementation.</p><p>I also recommend that you do other projects with Swift outside of “100 Days of Swift”. Coding other projects helped to further reinforce what I learned on 100 Days of Swift.</p><p>Lastly, keep track of what you are building and learning every day, it helps to refer back next time. I did so using a git repository, it’s a great way to hunt down previous resources, you can check out my<a href="https://github.com/acciohyun/100_Days_of_Swift"> projects with “100 Days of Swift”.</a></p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f1e4d2d3ee48" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating SwiftData and UIViewRepresentable in SwiftUI]]></title>
            <link>https://hyunleemia.medium.com/integrating-swiftdata-and-uiviewrepresentable-in-swiftui-e6125997bef9?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/e6125997bef9</guid>
            <category><![CDATA[swiftdata]]></category>
            <category><![CDATA[uicalendarview]]></category>
            <category><![CDATA[uiviewrepresentable]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Sat, 11 May 2024 09:21:53 GMT</pubDate>
            <atom:updated>2024-05-16T03:07:59.088Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>TLDR: How to read and update data persisted through SwiftData on a UICalendarView in SwiftUI (iOS 17.4)</blockquote><h3>Use case scenario</h3><p><strong>App name:</strong> Rapha for AS (currently available on the App Store)</p><p><strong>Target user:</strong> Users with Ankylosing Spondylitis</p><p><strong>Core feature:</strong> Users can record their symptoms, medication intake and lab results. They can also see their records at a glance on a calendar.</p><p><strong>Encountered issue: </strong>After a record is newly created, and the user goes back to the main view (showing the Calendar), the date decoration corresponding to the latest record did not appear. The date decoration only appeared after the previous or next month of the calendar is viewed (the calendar view updates).</p><p><strong>Original approach: </strong>Data saved through SwiftData was queried from the view conforming to UIViewRepresentable protocol (which enables the a UICalendarView instance to load on a SwiftUI environment). This same variable (containing the query results) was then passed into the delegate and coordinator methods that update the calendar and generate the date decorations.</p><h3>Source of the issue</h3><p>By investigating the process from data creation to data reading, I confirmed that the record created by the user was saved correctly by the model and that it was updated (almost) immediately in all other views.</p><p>This narrowed the issue to how the data was being accessed by the UICalendarView.</p><p>This is also where things got a little tricky because using a UICalendarView (as compared to a custom built calendar) meant that the lifecycle (creation, load, and update) of how the components of the UICalendarView is unknown.</p><p>The weirdest observation was that two separate UICalendarViewDelegate methods were called one after another and it turned out that one received the updated query results while the other was missing the latest record. (The method missing the latest record was responsible for updating the date decorations — which explained the issue I was experiencing)</p><p>This suggested that the issue was probably because of how the data was being passed to the UICalendarView or how the UICalendarView was accessing it. Again, how the UICalendarView access it was unknown so I continued experimenting on how the data was being passed to the view.</p><h3>The solution</h3><p>The solution was to <strong>assign the queried results to a property in an instance of a class that conforms to the ObservableObject protocol</strong>. When this property was passed into the UICalendarView instance, finally, the data was updated and consistent (both between the views and the actual model).</p><pre>//I created an object that conforms to ObservableObject protocol <br>//A property inside this object will hold the query data <br>// (manually reassigned each time the query data is updated<br><br>class RecordCopy: ObservableObject{<br>    @Published var allRecords = [CalendarDate]()<br>}<br><br>//CalendarView struct that now takes in data conforming to ObservableObject <br>//rather than directly from the SwiftData query<br>struct CalendarView: UIViewRepresentable{<br>    let interval: DateInterval<br>    @Environment(\.modelContext) private var modelContext<br>    @Query var recordsSaved: [CalendarDate]<br>    @Binding var selectedDate: Date<br>    @State var calendarView: UICalendarView?<br>    @Binding var recordCopyClass: RecordCopy <br><br>    func makeUIView(context: Context) -&gt; UICalendarView {<br>        let view = UICalendarView()<br>        DispatchQueue.main.asyncAfter(deadline: .now()){<br>            self.calendarView = view<br>        }<br>        let dateSelection = UICalendarSelectionSingleDate(delegate: context.coordinator)<br>        view.delegate = context.coordinator<br>        view.calendar = Calendar(identifier: .gregorian)<br>        view.availableDateRange = interval<br>        view.selectionBehavior = dateSelection<br>        dateSelection.selectedDate = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: Date())<br>        return view<br>    }<br>    <br>    <br>    func makeCoordinator() -&gt; Coordinator {<br>        Coordinator(parent: self, savedRecords: $recordCopyClass, selectedDate: $selectedDate)<br>    }<br>    <br>    func updateUIView(_ uiView: UICalendarView, context: Context) {<br>        uiView.reloadInputViews()<br>        uiView.invalidateIntrinsicContentSize()<br>        uiView.reloadDecorations(forDateComponents: recordCopyClass.allRecords.map{Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: $0.date)}, animated: true)<br>    }<br>    <br>    func updateView() {<br>        calendarView?.reloadInputViews()<br>    }<br>    <br>    class Coordinator: NSObject, UICalendarViewDelegate, UICalendarSelectionSingleDateDelegate{<br>        <br>        //this is the CalendarViewDelegate<br>        var parent: CalendarView<br>        @Binding var savedRecordsCopy: RecordCopy<br>        private var filteredRecords: [CalendarDate]?<br>        let calculations = RecordsModel()<br>        @Binding var selectedDate: Date<br>        <br>        <br>        init(parent: CalendarView, savedRecords: Binding&lt;RecordCopy&gt;, selectedDate: Binding&lt;Date&gt;) {<br>            self.parent = parent<br>            self._savedRecordsCopy = savedRecords<br>            self._selectedDate = selectedDate<br>        }<br>        <br>        @MainActor<br>        func calendarView(_ calendarView: UICalendarView, decorationFor dateComponents: DateComponents) -&gt; UICalendarView.Decoration? {<br>            let record = savedRecordsCopy.allRecords.filter{$0.date.startOfDay == dateComponents.date?.startOfDay}<br>            if record.isEmpty{return nil}<br>            let renderer = ImageRenderer(content: CalendarCellRecordsView(record: record[0]))<br>            renderer.scale = 3<br>            if let uiImage = renderer.uiImage {<br>                return .image(uiImage)<br>            }<br>            return nil<br>        }<br>        <br>        func dateSelection(_ selection: UICalendarSelectionSingleDate, canSelectDate dateComponents: DateComponents?) -&gt; Bool {<br>            return true<br>        }<br>        <br>        @MainActor<br>        func dateSelection(_ selection: UICalendarSelectionSingleDate, didSelectDate dateComponents: DateComponents?) {<br>            if let date = dateComponents{<br>                if let selectedDate = Calendar.current.date(from: dateComponents!)?.startOfDay{<br>                    DispatchQueue.main.async{<br>                        self.selectedDate = selectedDate<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p>I believe the issue was because the data being passed into the UICalendarView instance did not conform to ObservableObject protocol.</p><p>When persisting data using SwiftData, the data instances saved conform to ObservableObject but when queried, the results are stored in an array. The array itself does not conform to ObservableObject protocol and I suspect that is why such weird data behaviour was observed.</p><h3>Conclusion</h3><p>SwiftData is a very convenient way to persist data within a SwiftUI environment. Especially because any data updates made through the app is synced with the database with few lines of code. In any view, you can confident that the data is reliable.</p><p>It’s not as straightforward when you want to implement SwiftData CRUD with a UIKit instance brought into SwiftUI. I expected that the data sharing and updating would be as seamless (like how it was in native SwiftUI components) but it turns out that you have to jump through some hurdles.</p><p>If you’d like to take a deeper look at the code, you can do so on my <a href="https://github.com/acciohyun/Rapha">Github page here!</a></p><p>Thanks, and have a great day :-)</p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e6125997bef9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Flows using Property Wrappers in SwiftUI]]></title>
            <link>https://hyunleemia.medium.com/data-flows-using-property-wrappers-in-swiftui-252188f899b1?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/252188f899b1</guid>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Fri, 26 Apr 2024 12:21:21 GMT</pubDate>
            <atom:updated>2024-04-28T09:26:48.693Z</atom:updated>
            <content:encoded><![CDATA[<p>Property wrappers are used in SwiftUI to control the data flows, manage states, and update views.</p><p>In this article, I explain property wrappers that I frequently utilise when developing apps in SwiftUI and also share insights on their use cases (based on my experience 🤓).</p><blockquote>TLDR: This article covers @State @Binding @Environment @EnvironmentObject</blockquote><h3>@State and @Binding</h3><h4>❓What are they?</h4><p>@State property wrapper is used to declare variables that will change in a SwiftUI view. When these variables are changed by user input/other programmatic logic, components of the view that are dependent on these variables will be updated.</p><p>@Binding property wrapper is used to declare a variable that will receive its value from a parent/previous view. It ensures that any changes made to this variable in the second view updates the corresponding variable in the parent view. Vice versa, when the variable in the parent view changes, the corresponding variable in the child view also changes.</p><p>Note that @State does not only have to be used when passing variables between views. A variable that changes due to programmatic events within the same view should also have the @State property wrapper for Swift to recognise that it is a mutable property.</p><h4>🤔 When to use them</h4><ol><li>For simple View1 to View2 data flows. <br>In my experience, using a combination of @State and @Binding is most useful for simple data flow between two views. If the same variable has to be shared across multiple views, I find it easier to manage using other property wrappers (introduced later in this article)</li><li>For SwiftUI provided views that accept user input<br>In this case, I am not explicitly declaring an @Binding variable within the view. Controls pre-built by SwiftUI often utilises @Binding to facilitate the data flows between a view and its child components which requires user input.</li></ol><h4>👀 Example code and app</h4><p>Here’s an example of a simple app with two views.</p><p>View1 shows my name and allows me to navigate to View2 where I can <em>change</em> my name.</p><p>Changes made in View2 are reflected in View1.</p><pre>import SwiftUI<br><br>struct View1: View {<br>    @State var myName: String = &quot;Hyun&quot;<br>    <br>    var body: some View {<br>        NavigationStack {<br>            VStack {<br>                Text(&quot;My name: \(myName)&quot;)<br>                NavigationLink(&quot;Change my name&quot;, destination: View2(changedName: $myName))<br>            }.navigationTitle(&quot;VIEW 1&quot;)<br>        }<br>    }<br>}<br><br>struct View2: View {<br>    @Binding var changedName: String<br>    <br>    var body: some View {<br>        VStack {<br>            List{<br>                Section{<br>                    TextField(&quot;Title: &quot;, text: $changedName)<br>                } header:{<br>                    Text(&quot;Change my name: &quot;)<br>                }<br>            }<br>        }.navigationTitle(&quot;VIEW 2&quot;)<br>    }<br>}</pre><p>Bonus: Here’s a screen capture of how this looks</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*ln6O5SM80CSj7K_THnHvdA.gif" /></figure><h3>@Environment</h3><h4>❓What is it?</h4><p>@Environment property wrapper is used to reach pre-defined, Core Data managed objects in the app’s environment.</p><h4>🤔 When to use it</h4><p>The use cases of this property wrapper is specific and simple — when you need to reach into any of the existing variables in the app’s environment. You can check the list of <a href="https://developer.apple.com/documentation/swiftui/environmentvalues/">what is available in the Apple documentation.</a></p><h4>👀 Example code</h4><p>Here’s a real example of reaching into a pre-defined Environment Value in the app.</p><p>In order to use SwiftData to persist data in the user’s device, we have to create a model container within the app’s environment.</p><p>The app’s model context to knows where to store and access the model container.</p><pre>import SwiftUI<br>import SwiftData<br><br>struct CalendarScreen: View {<br>    @Environment(\.modelContext) var modelContext<br>    @Query var allRecords: [CalendarDate]<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;First Item: \(allRecords[0].date)&quot;)<br>        }<br>    }<br>}</pre><h3>@EnvironmentObject</h3><h4>❓What is it?</h4><p>@EnvironmentObject property wrapper allows us to create and access custom variables from the app’s environment — making it accessible from any view in the app.</p><p>It also automatically updates components that depend on this variable when the variable is updated.</p><h4>🤔 When to use it</h4><p>I tend to use the @EnvironmentObject property wrapper to share and update data across many views.</p><p>One use case that I repeatedly use is controlling the app’s navigation path using a Router object. The Router object keeps track of the view stacks and I use it to pop back to the HomeView from any view in the stack.</p><p>Since it has to be accessed and updated by all the views in my app, it is simpler to declare it as an @EnvironmentObject rather than passing it as a parameter to all the views.</p><h4>👀 Example code</h4><p>Here’s an example of how I use the @EnvironmentObject property wrapper to implement the Router pattern.</p><p>First, we create an object that will store our path, including a method that helps us to pop back to the root.</p><pre>class Router: ObservableObject{<br>    @Published var path: NavigationPath = NavigationPath()<br>    <br>    func backToRoot(){<br>        print(&quot;back to root&quot;)<br>        self.path = NavigationPath()<br>    }<br>}</pre><p>Next, initialise it at the app structure. Note that we have to declare it as a @StateObject and pass it in to the next view using the .environmentObject() method.</p><pre>struct MyApp: App {<br>    @StateObject var router = Router()<br>    var design = DesignModel()<br>    var body: some Scene {<br>        WindowGroup {<br>            StartView().environmentObject(router).accentColor(design.mainAccentColor)<br>        }<br>    }<br>}</pre><p>Lastly, here is an example of how it can be accessed and updated in a view.</p><pre>import SwiftUI <br><br>struct ChoosingView: View {<br>    @EnvironmentObject var router: Router<br>    var songName: String<br>    @State var nextView = false<br>    <br>    var body: some View {<br>        VStack{<br>            Text(&quot;Your music jam: \(data)&quot;)<br>            Text(&quot;Confirm&quot;)<br>                .onTapGesture{<br>                    nextView = true<br>                }<br>                .padding()<br>        }.navigationDestination(isPresented: $nextView){<br>            PlaylistView(songName: songName).environmentObject(router)<br>        }<br>    }<br>}</pre><h3>Share your insights with the community!</h3><p>When used properly, SwiftUI’s property wrappers are powerful tools that help us to manage our data and states in our app effectively.</p><p>While developing SwiftUI apps, I realised how some of these property wrappers are more suitable for certain use cases than others. I also noticed how developer new to SwiftUI struggle to understand when to use which property wrapper (that was me too!) That spurred me to share some of the insights I’ve gained while developing SwiftUI apps.</p><p>If you have any other use cases for these property wrappers (or others that I’ve yet to mention), feel free to leave a comment and keep the rest of the community informed!</p><h3>Connect with me!</h3><p>Thanks for reading. If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=252188f899b1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World!]]></title>
            <link>https://hyunleemia.medium.com/hello-world-00735e60a686?source=rss-19b58353dd92------2</link>
            <guid isPermaLink="false">https://medium.com/p/00735e60a686</guid>
            <category><![CDATA[apple-developer-academy]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Hyun Lee (Mia)]]></dc:creator>
            <pubDate>Thu, 11 Apr 2024 13:57:59 GMT</pubDate>
            <atom:updated>2024-04-19T12:24:04.945Z</atom:updated>
            <content:encoded><![CDATA[<p>I am Hyun (aka Mia), and I am currently a Learner in the Apple Developer Academy @ POSTECH.</p><p>As an aspiring iOS developer, I’ve decided to use this space to publish meaningful content related to iOS app development and launch.</p><p>Watch this space for interesting content and discourse!</p><p>P.S. Here’s a photo from the Apple Developer Academy space @ POSTECH (Pohang, South Korea) that I took on my first week here 🤓</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zb-Rf4l2xYyzZoccliLvmg.jpeg" /></figure><h4><strong>Connect with me!</strong></h4><p>If you enjoyed my article and are interested in my journey as an engineer, feel free to connect with me on <a href="https://www.linkedin.com/in/hyun-lee7799/">LinkedIn</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=00735e60a686" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>