<?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 Joshua Hart on Medium]]></title>
        <description><![CDATA[Stories by Joshua Hart on Medium]]></description>
        <link>https://medium.com/@emt.joshhart?source=rss-7dfdfde67f1b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*QEoNKF6XTIzQCS_Qh4r6MQ.jpeg</url>
            <title>Stories by Joshua Hart on Medium</title>
            <link>https://medium.com/@emt.joshhart?source=rss-7dfdfde67f1b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 17:35:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@emt.joshhart/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[A Comprehensive Guide to Apple’s New Privacy Manifest Requirements for iOS App Developers]]></title>
            <link>https://medium.com/@emt.joshhart/a-comprehensive-guide-to-apples-new-privacy-manifest-requirements-for-ios-app-developers-d004dc47ad35?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d004dc47ad35</guid>
            <category><![CDATA[swift-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Sat, 29 Jul 2023 00:39:35 GMT</pubDate>
            <atom:updated>2023-09-18T02:01:43.073Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*c3Oe9eYbf4zG8XYT" /><figcaption>Photo by <a href="https://unsplash.com/@szolkin?utm_source=medium&amp;utm_medium=referral">Sergey Zolkin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>YOU are NOT prepared for Apple’s New Privacy Requirements for iOS App Developers: Comprehensive Guide</h3><p>As an iOS app developer, one of the most vital parts of your role is to ensure that your app aligns with Apple’s stringent policies and guidelines. In recent years, Apple has placed significant emphasis on user privacy and has mandated a number of new rules designed to offer more transparency about the data collection practices of iOS apps. In this context, Apple has introduced new privacy requirements for app developers that necessitate declaring the data collected by your app or any third-party Software Development Kits (SDKs) used.</p><h3>Understanding the New Privacy Requirements</h3><p>Apple’s new privacy requirements focus on the declaration of the data collected by your app, which is documented in the ‘privacy manifest’. The privacy manifest is a report that outlines the categories of data your app and third-party SDKs collect about the user, and the reasons for collecting this data. As an app developer, you need to create this privacy report using Xcode, Apple’s Integrated Development Environment (IDE).</p><p>The data collection practices are divided into different categories such as ‘Contact Info’, ‘Health &amp; Fitness’, ‘Financial Info’, ‘Location’, ‘Sensitive Info’, ‘Contacts’, ‘User Content’, ‘Browsing History’, ‘Search History’, ‘Identifiers’, ‘Purchases’, ‘Usage Data’, ‘Diagnostics’, and ‘Other Data Types’. Each category encompasses specific data types that your app may collect.</p><p>The reasons for collecting this data are categorized as ‘Third-Party Advertising’, ‘Developer’s Advertising or Marketing’, ‘Analytics’, ‘Product Personalization’, ‘App Functionality’, and ‘Other Purposes’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/1*sombPl6epHJ3r00hGAMqgw@2x.jpeg" /></figure><h3>Step-by-Step Guide to Compliance</h3><h3>Step 1: Review Your App’s Data Collection Practices</h3><p>Begin with a comprehensive review of your app’s data collection practices. You need to scrutinize not only the data collected by your app, but also the data collected by any third-party SDKs that your app uses.</p><p>Remember, third-party SDKs need to provide their <em>own</em> privacy manifest files, <strong>and your app’s privacy manifest doesn’t need to cover data collected by third-party SDKs.</strong></p><blockquote>From <a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests">Apple</a>:<br>Important</blockquote><blockquote>Third-party SDKs need to provide their own privacy manifest files that record the types of data they collect. Your app’s privacy manifest file doesn’t need to cover data collected by third-party SDKs that your app links to.</blockquote><h3>Step 2: Identify the Categories of Data Your App Collects</h3><p>Your next step is to identify the categories of data that your app collects.</p><p>To get started, you will need to add a dictionary to the NSPrivacyCollectedDataTypes array in your privacy information file for each type of data your app or SDK collects.</p><p>In this dictionary, you&#39;ll add the following keys: NSPrivacyCollectedDataType, NSPrivacyCollectedDataTypeLinked, NSPrivacyCollectedDataTypeTracking, and NSPrivacyCollectedDataTypePurposes.</p><p>Let’s break down some examples based on these categories:</p><h3><strong>CONTACT INFORMATION:</strong></h3><p>If your app collects user’s names, you will categorize this data as follows:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeName</li></ul><p>If your app collects user’s email addresses:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeEmailAddress</li></ul><h3><strong>HEALTH &amp; FITNESS:</strong></h3><p>If your app collects user’s health and medical data, perhaps through the HealthKit API:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeHealth</li></ul><p>If your app collects user’s fitness and exercise data, maybe via the Motion and Fitness API:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeFitness</li></ul><h3><strong>FINANCIAL INFORMATION:</strong></h3><p>If your app collects user’s payment info such as form of payment, payment card number, or bank account number:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypePaymentInfo</li></ul><p>If your app collects other financial information such as salary, income, assets, or debts:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeOtherFinancialInfo</li></ul><h3><strong>LOCATION:</strong></h3><p>If your app collects user’s precise location:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypePreciseLocation</li></ul><p>If your app collects user’s coarse location:</p><ul><li>NSPrivacyCollectedDataType: NSPrivacyCollectedDataTypeCoarseLocation</li></ul><p>Remember, it’s crucial to be honest and precise about the data your app collects. <em>Misrepresenting your app’s data collection can lead to penalties, and more importantly, it can erode trust with your users.</em></p><p>Once you’ve identified the data types your app collects, the next steps would be to specify whether this data type is linked to the user’s identity (NSPrivacyCollectedDataTypeLinked), and whether your app or SDK uses this data type to track the user (NSPrivacyCollectedDataTypeTracking).</p><p>In the next step, you should also identify the reasons your app collects this data by providing an array of strings for the NSPrivacyCollectedDataTypePurposes key, choosing from the list of purposes provided by Apple.</p><p>All these steps are critical in crafting your app’s privacy report, which helps maintain transparency and trust with your users. In the next part of this guide, we will walk through the process of generating this privacy report.</p><h3>Step 3: Add the Relevant Keys to the Dictionary</h3><p>The dictionaries you create for each data type should include four keys:</p><ol><li><strong>NSPrivacyCollectedDataType</strong>: A string that identifies the type of data your app collects. This should be chosen from the provided list of data types.</li><li><strong>NSPrivacyCollectedDataTypeLinked</strong>: A Boolean that indicates whether this data type is linked to the user’s identity.</li><li><strong>NSPrivacyCollectedDataTypeTracking</strong>: A Boolean that indicates whether this data type is used for tracking purposes.</li><li><strong>NSPrivacyCollectedDataTypePurposes</strong>: An array of strings that list the reasons your app collects the data. The reasons should be chosen from the provided list of purposes.</li></ol><p>Remember, you should only use values from Apple’s provided lists for the NSPrivacyCollectedDataType and NSPrivacyCollectedDataTypePurposes keys. <em>Defining your own data types or reasons will prevent Xcode from generating a correct privacy report.</em></p><h3>EXAMPLE:</h3><p>Here is an example for an app that would be collecting the user’s name, email, phone number and location data:</p><pre>{<br>  &quot;NSPrivacyCollectedDataTypes&quot;: [<br>    {<br>      &quot;NSPrivacyCollectedDataType&quot;: &quot;NSPrivacyCollectedDataTypeName&quot;,<br>      &quot;NSPrivacyCollectedDataTypeLinked&quot;: true,<br>      &quot;NSPrivacyCollectedDataTypeTracking&quot;: false,<br>      &quot;NSPrivacyCollectedDataTypePurposes&quot;: [<br>        &quot;NSPrivacyCollectedDataTypePurposeAppFunctionality&quot;<br>      ]<br>    },<br>    {<br>      &quot;NSPrivacyCollectedDataType&quot;: &quot;NSPrivacyCollectedDataTypeEmailAddress&quot;,<br>      &quot;NSPrivacyCollectedDataTypeLinked&quot;: true,<br>      &quot;NSPrivacyCollectedDataTypeTracking&quot;: false,<br>      &quot;NSPrivacyCollectedDataTypePurposes&quot;: [<br>        &quot;NSPrivacyCollectedDataTypePurposeAppFunctionality&quot;,<br>        &quot;NSPrivacyCollectedDataTypePurposeDeveloperAdvertising&quot;<br>      ]<br>    },<br>    {<br>      &quot;NSPrivacyCollectedDataType&quot;: &quot;NSPrivacyCollectedDataTypePhoneNumber&quot;,<br>      &quot;NSPrivacyCollectedDataTypeLinked&quot;: true,<br>      &quot;NSPrivacyCollectedDataTypeTracking&quot;: false,<br>      &quot;NSPrivacyCollectedDataTypePurposes&quot;: [<br>        &quot;NSPrivacyCollectedDataTypePurposeAppFunctionality&quot;<br>      ]<br>    },<br>    {<br>      &quot;NSPrivacyCollectedDataType&quot;: &quot;NSPrivacyCollectedDataTypePreciseLocation&quot;,<br>      &quot;NSPrivacyCollectedDataTypeLinked&quot;: true,<br>      &quot;NSPrivacyCollectedDataTypeTracking&quot;: true,<br>      &quot;NSPrivacyCollectedDataTypePurposes&quot;: [<br>        &quot;NSPrivacyCollectedDataTypePurposeAppFunctionality&quot;<br>      ]<br>    }<br>  ]<br>}</pre><h3>Step 4: Generate Your App’s Privacy Report</h3><p>Once you’ve completed these steps, you’re ready to generate your app’s privacy report. This can be done directly in Xcode by following these steps:</p><ol><li>Open your project in Xcode.</li><li>Choose Product &gt; Archive. Xcode will create the archive and reveal it in the organizer.</li><li>Control-click the archive in the organizer and choose Generate Privacy Report.</li><li>Choose a location to save the privacy report.</li><li>Switch to Finder and navigate to the location where you saved the privacy report. Double-click to open the report in Preview.</li></ol><p>The generated privacy report will be organized similarly to the Privacy Nutrition Labels you might have seen on the App Store. Refer to this report when you provide your app’s privacy details in App Store Connect.</p><h3>Step 5: Provide Your App’s Privacy Details in App Store Connect</h3><p>The final step in this process is to provide your app’s privacy details in App Store Connect. The privacy report you generated in the previous step will guide you in this process. Providing accurate privacy details in App Store Connect is crucial, as it allows users to understand what data your app collects and why.</p><h3>Staying Updated with Apple’s Privacy Requirements</h3><p>Apple’s commitment to user privacy means that their guidelines and requirements for app developers may be updated regularly. As an app developer, it’s essential to keep abreast of any changes and ensure that your app stays in compliance with these requirements.</p><h3>Helpful Links:</h3><ul><li><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_use_of_required_reason_api">Describing use of required reason API</a></li><li><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files/describing_data_use_in_privacy_manifests">Describing data use in privacy manifests</a></li><li><a href="https://developer.apple.com/documentation/bundleresources/privacy_manifest_files#4284009">Privacy manifest files</a></li></ul><h3>Conclusion</h3><p>With how serious Apple is with Privacy these days, it’s best to be at the forefront of this wave, instead of trying to fight for air after the wave has hit. The addition of the privacy manifest to Apple’s guidelines demonstrates their commitment to user privacy and transparency. While the new requirements may necessitate some additional work, adhering to these guidelines can build trust with your app’s users, ultimately leading to better engagement and success for your app. By following this guide, you should be well-prepared to navigate the new privacy requirements and ensure your app’s compliance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d004dc47ad35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering MVC in iOS Swift Development: From Basics to Best Practices]]></title>
            <link>https://medium.com/@emt.joshhart/mastering-mvc-in-ios-swift-development-from-basics-to-best-practices-489217e9a3b9?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/489217e9a3b9</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[model-view-controller]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Fri, 19 May 2023 00:32:14 GMT</pubDate>
            <atom:updated>2023-05-19T00:32:14.293Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3BANaxWvN00OfjMAm8mBhQ.jpeg" /></figure><p>Welcome, iOS developers! Among the various design patterns available for structuring your iOS Swift application, Model-View-Controller (MVC) is one of the most popular and often used. Understanding MVC can significantly improve the structure and quality of your code. This article aims to guide you through the core principles of MVC, its role in organizing your project, and its strengths and limitations.</p><h3>Understanding MVC</h3><p>MVC stands for Model-View-Controller. This design pattern breaks an application into three interconnected components: Models, Views, and Controllers. This division helps manage complexities when designing applications and provides a clean separation of concerns.</p><ul><li>Model: The heart of the pattern, the Model, encompasses the business logic. It is responsible for retrieving and manipulating data. Importantly, the Model doesn’t know anything about the user interface or how the data will be presented.</li><li>View: The View represents the user interface and anything the user interacts with on the screen. It displays the data and sends user actions back to the Controller.</li><li>Controller: The Controller is the binding element between the Model and the View. It updates the View with data from the Model and updates the Model with data from user actions.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*POjydcylYY14UN9W.png" /></figure><h3>TikTok: Real Life Analogy of MVC:</h3><p><strong>Model</strong> — The Model is the video content that a TikTok creator makes. This includes the video file itself, the sound or music used, the captions, hashtags, and other details. It represents the raw data or content that the creator wants to share with the world.</p><p><strong>View </strong>— The View is the TikTok app interface where the audience watches and interacts with the videos. It presents the video content (Model) to the audience in a user-friendly format. The same video can be viewed in different ways on the app: on the creator’s profile, on the follower’s feed, or on the “For You” page.</p><p><strong>Controller</strong> — The TikTok creator acts as the Controller. They decide what content to make (updating the Model), and they interact with their followers (updating the View). The Controller handles the user interactions, like responding to comments, editing their video details, or deleting videos.</p><p>So in a sense, TikTok operates much like an MVC system, with the creators (Controllers) providing content (Models) to the viewers (Views).</p><h3>Organizing Your Project with MVC</h3><p>Adopting the MVC design pattern significantly influences your project’s structure, contributing to its manageability. At a basic level, each MVC component should have its separate group or directory in the project:</p><ul><li>Model: This folder contains data objects, business logic, and data persistence code.</li><li>View: This directory hosts UI-related code, including Storyboards, XIBs, and custom UIView subclasses.</li><li>Controller: This group contains ViewControllers and any other “glue” code.</li></ul><blockquote><strong><em>However, for larger projects with many features or functionalities, a flat directory structure with only Model, View, and Controller folders will not be the most efficient way to organize your code. Instead, it can be beneficial to structure your project around features or modules, with each feature having its own MVC structure.</em></strong></blockquote><blockquote>For example:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*ByG5XvqDW-9iPSS_Ii7TBw.png" /><figcaption>A search feature could have many screens, many models, different controllers.</figcaption></figure><p>This feature-based modular organization can make your codebase much easier to navigate, maintain, and scale. Each module can be developed and tested independently, making it an excellent structure for collaborative environments.</p><h3>When to Use MVC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*UFMR9UMNGlHNrBdmYZC4rA.jpeg" /></figure><p>MVC is particularly well-suited for small to medium-sized applications with uncomplicated business logic. Its clear and concise structure allows for a fast development process, offering a quick start with a well-organized codebase. MVC can also shine when you’re prototyping or developing MVPs (Minimum Viable Products), as the separation of concerns allows you to iterate quickly and change parts of your application without impacting others.</p><h3>Limitations of MVC</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z0u5cTsD4Fl_CHEsroyo_g.png" /></figure><p>For large, complex applications, the Controller can often become bloated — a problem known as “Massive View Controller.” This issue arises when the Controller takes on too many responsibilities, leading to code that is hard to understand, test, and debug. MVC might also fall short when dealing with sophisticated user interfaces or real-time updates, where a more reactive or component-based pattern might be more beneficial.</p><h3>MVC and Team Collaboration</h3><p>MVC can provide a solid foundation for team collaboration by clearly defining responsibilities, thus minimizing the overlap between different areas of an application. However, for larger teams or more complex projects, MVC may pose challenges. Bloated Controllers can lead to multiple developers needing to work on the same file simultaneously, increasing the risk of merge conflicts.</p><h3>In Conclusion</h3><p>Understanding MVC’s strengths, weaknesses, and best use cases are essential when deciding whether it’s the right fit for your iOS project. While it can serve as an excellent starting point, especially for smaller projects, it’s crucial to be open to exploring other design patterns (like MVVM, VIPER) that might be more suited to larger, more complex applications.</p><p>The best design pattern depends on the nature of your project, your team’s preferences, and the specific problem you’re trying to solve. Through this article, we hope you’ve gained a better understanding of the Model-View-Controller pattern, its role in structuring your iOS Swift projects, and how to use it effectively.</p><p>In the end, remember that the goal of any architectural pattern, including MVC, is to make your code more understandable, scalable, and maintainable. Choose the one that best helps you achieve these objectives for your specific project and team.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=489217e9a3b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Create A Horizontal Scroll View]]></title>
            <link>https://medium.com/@emt.joshhart/swift-create-a-horizontal-scroll-view-209b84cfe396?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/209b84cfe396</guid>
            <category><![CDATA[uibutton]]></category>
            <category><![CDATA[horizontal-scrolling]]></category>
            <category><![CDATA[linkedin]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Sun, 26 Mar 2023 03:22:32 GMT</pubDate>
            <atom:updated>2023-04-08T12:33:42.142Z</atom:updated>
            <content:encoded><![CDATA[<p>LinkedIn AnswerPreface:</p><p>This code is being quickly provided in response to a LinkdIn Question. <em>More content to be added in the future.</em></p><h3>The Magical Reuseable Class:</h3><pre>import UIKit<br><br>/// The horizontal scroll view subclasses the UIScrollView and adds your views using<br>/// programmatic NSLayoutConstraints.<br>/// - Important: Setting a height constraint on this view is highly recommended.<br>/// It would also be recommended to set a width constraint on your added arrangedViews.<br>class HorizontalScrollView: UIScrollView {<br>    /// The views that have been added to this scroll view.<br>    var arrangedViews: [UIView] = []<br>    /// The constraints added as a result of the arrangedViews added.<br>    private var arrangedViewContraints: [NSLayoutConstraint] = []<br>    /// The spacing between views, defaults to 8.0.<br>    var interItemSpacing: CGFloat = 8.0 { didSet { setNeedsUpdateConstraints() } }<br>    /// The content inset around the arranged views within the scroll view.<br>    var contentInsetValue: UIEdgeInsets = .init(top: 0, left: 10, bottom: 0, right: 0) {<br>        didSet { contentInset = contentInsetValue }<br>    }<br><br>    // MARK: - INITIALIZERS:<br><br>    override init(frame: CGRect) {<br>        super.init(frame: frame)<br>        delaysContentTouches = false<br>        contentInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 0)<br>    }<br><br>    @available(*, unavailable) required init?(coder: NSCoder) { nil }<br><br>    // MARK: - OVERRIDES OF INHERITANCE:<br><br>    override open func updateConstraints() {<br>        super.updateConstraints()<br>        removeConstraintsForArrangedViews()<br>        addConstraintsForArrangedViews()<br>    }<br><br>    // MARK: - EXPOSED FUNCTIONS:<br><br>    /// Add the views you want to the scrolling horizontal view.<br>    /// The views are automatically added on the main queue.<br>    /// - Parameter views: ([UIView]) The arrays of views you want to add.<br>    func addArrangedViews(_ views: [UIView]) {<br>        DispatchQueue.main.async {<br>            views.forEach {<br>                $0.translatesAutoresizingMaskIntoConstraints = false<br>                self.arrangedViews.append($0)<br>                self.addSubview($0)<br>            }<br>            self.setNeedsUpdateConstraints()<br>        }<br>    }<br><br>    /// Removes the view at a specified index with a boolean returned in the completion handler.<br>    /// The view is automatically removed on the main thread.<br>    /// - Parameter index: (Int) The index of the view you would like to remove.<br>    /// - Parameter completion: (optional)  Returns true if the view was removed, false if not found.<br>    func removeView(index: Int, completion: ((Bool) -&gt; Void)? = nil) {<br>        guard let view = self.arrangedViews[safe: index] else {<br>            completion?(false)<br>            return<br>        }<br>        view.alpha = 1.0<br>        UIView.animate(withDuration: 0.35, delay: 0, options: .curveEaseOut, animations: {<br>            view.alpha = 0<br>        }, completion: { [weak self] _ in<br>            DispatchQueue.main.async {<br>                self?.arrangedViews.remove(at: index)<br>                view.removeFromSuperview()<br>                self?.updateConstraints()<br>                completion?(true)<br>            }<br>        })<br>    }<br><br>    /// Removes all arranged views, with the option of leaving the first view.<br>    /// Leaving the first view could be handy when your first view features a button<br>    /// like &quot;Add a photo&quot; while the views following it are photos.<br>    /// Arranged views are removed on the main thread.<br>    /// - Parameter exceptFirstView: (Bool) Pass true to preserve the first view.<br>    func removeAllArrangedViews(exceptFirstView: Bool = true) {<br>        DispatchQueue.main.async {<br>            guard let first = self.arrangedViews.first else { return }<br>            self.arrangedViews = exceptFirstView ? [first] : []<br>            for subview in self.subviews {<br>                if exceptFirstView, subview == first { continue }<br>                subview.removeFromSuperview()<br>            }<br><br>            self.updateConstraints()<br>        }<br>    }<br><br>    /// Removes all the constraints for the arranged views.<br>    private func removeConstraintsForArrangedViews() {<br>        arrangedViewContraints.forEach { $0.isActive = false }<br>        arrangedViewContraints.removeAll()<br>    }<br><br>    /// Adds all the constraints for the arranged views and updates the array of NSLayoutConstraints.<br>    private func addConstraintsForArrangedViews() {<br>        for (index, view) in arrangedViews.enumerated() {<br>            switch index {<br>            case 0:<br>                arrangedViewContraints.append(leadingConstraint(forView: view))<br>                arrangedViewContraints.append(topConstraint(forView: view))<br>            case arrangedViews.count - 1:<br>                arrangedViewContraints.append(trailingConstraint(forView: view))<br>                arrangedViewContraints.append(topConstraint(forView: view))<br>                fallthrough<br>            default:<br>                let previousView = arrangedViews[index - 1]<br>                let constraint = leadingToTrailingConstraint(forView: view, toView: previousView)<br>                arrangedViewContraints.append(constraint)<br>            }<br>        }<br>    }<br><br>    // MARK: - CONSTRAINT HELPERS:<br>    // It would be wise to leave these helpers as you utilize this class<br>    // across mutliple projects, instead of adding them as extensions.<br><br>    /// Creates a leading constraint horizontally from one views leading edge to another views trailing edge.<br>    /// - Parameter arrangedView: (UIView) The view that should have the leading constraint.<br>    /// - Parameter toView: (UIView)  The view that should have the trailing constraint.<br>    /// - Important: This function activates the constraint.<br>    /// - Returns: (NSLayoutConstraint) The horizontal NSLayoutConstraint.<br>    private func leadingToTrailingConstraint(forView arrangedView: UIView,<br>                                             toView: UIView) -&gt; NSLayoutConstraint {<br>        let constraint = arrangedView.leadingAnchor<br>            .constraint(equalTo: toView.trailingAnchor, constant: interItemSpacing)<br>        constraint.isActive = true<br>        return constraint<br>    }<br><br>    /// Creates a top constraint from the passed view&#39;s top edge to this class&#39;s top edge.<br>    /// - Parameter arrangedView: (UIView) The view that should have the top constraint.<br>    /// - Important: This function activates the constraint.<br>    /// - Returns: (NSLayoutConstraint) The top NSLayoutConstraint.<br>    private func topConstraint(forView arrangedView: UIView) -&gt; NSLayoutConstraint {<br>        let constraint = arrangedView.topAnchor.constraint(equalTo: self.topAnchor)<br>        constraint.isActive = true<br>        return constraint<br>    }<br><br>    /// Creates a leading constraint from the passed view&#39;s leading edge to this class&#39;s leading edge.<br>    /// - Parameter arrangedView: (UIView) The view that should have the leading constraint.<br>    /// - Important: This function activates the constraint.<br>    /// - Returns: (NSLayoutConstraint) The leading NSLayoutConstraint.<br>    private func leadingConstraint(forView arrangedView: UIView) -&gt; NSLayoutConstraint {<br>        let constraint = arrangedView.leadingAnchor.constraint(equalTo: self.leadingAnchor)<br>        constraint.isActive = true<br>        return constraint<br>    }<br><br>    /// Creates a trailing constraint from the passed view&#39;s trailing edge to this class&#39;s trailing edge.<br>    /// - Parameter arrangedView: (UIView) The view that should have the trailing constraint.<br>    /// - Important: This function activates the constraint.<br>    /// - Returns: (NSLayoutConstraint) The trailing NSLayoutConstraint.<br>    private func trailingConstraint(forView arrangedView: UIView) -&gt; NSLayoutConstraint {<br>        let constraint = arrangedView.trailingAnchor.constraint(equalTo: self.trailingAnchor)<br>        constraint.isActive = true<br>        return constraint<br>    }<br>}<br><br>private extension Collection {<br>    /// Returns the element at the specified index if it is within bounds, otherwise nil.<br>    subscript (safe index: Index) -&gt; Element? {<br>        return indices.contains(index) ? self[index] : nil<br>    }<br>}</pre><h3>Example Of Use:</h3><p>Simply add ButtonHorizontalScrollingView to your subview afterwards.</p><pre>import UIKit<br><br>class ButtonHorizontalScrollingView: UIView {<br>    let allButtonStyles = ButtonType.allCases<br>    let scrollingView = HorizontalScrollView(frame: .zero)<br><br>    init() {<br>        super.init(frame: .zero)<br>        self.buildUserInterface()<br>    }<br><br>    @available(*, unavailable) required init?(coder: NSCoder) { nil }<br><br>    private func buildUserInterface() {<br>        let buttons = allButtonStyles.compactMap { createButton(style: $0) }<br>        scrollingView.translatesAutoresizingMaskIntoConstraints = false<br>        scrollingView.addArrangedViews(buttons)<br>        scrollingView.isUserInteractionEnabled = true<br>        scrollingView.interItemSpacing = 10<br>        scrollingView.height(36)<br>        scrollingView.showsHorizontalScrollIndicator = false<br>        self.addSubview(scrollingView)<br>        scrollingView.leadingAnchor.constraint(equalTo: self.leadingAnchor).isActive = true<br>        scrollingView.trailingAnchor.constraint(equalTo: self.trailingAnchor).isActive = true<br>        scrollingView.topAnchor.constraint(equalTo: self.topAnchor, constant: 8).isActive = true<br>        scrollingView.bottomAnchor.constraint(equalTo: self.bottomAnchor, constant: -8).isActive = true<br>    }<br><br>    private func createButton(style: ButtonType) -&gt; UIButton {<br>        var configuration = UIButton.Configuration.plain()<br>        configuration.background.cornerRadius = 8<br>        configuration.background.backgroundColor = .darkGray // background color<br>        let font = UIFont.systemFont(ofSize: 13, weight: .semibold)<br>        let container = AttributeContainer([NSAttributedString.Key.font: font])<br>        configuration.attributedTitle = AttributedString(style.text, attributes: container)<br>        configuration.baseForegroundColor = .white // text color<br>        let button = UIButton(configuration: configuration)<br>        return button<br>    }<br>}<br><br>enum ButtonType: Int, CaseIterable {<br>    case fashionStyle,<br>         sportyChic,<br>         muaythaiTraining,<br>         backStretches,<br>         boxingLifestyle,<br>         shadowBoxing,<br>         officeOutfit,<br>         workwearStyle<br><br>    var text: String {<br>        switch self {<br>        case .fashionStyle: return &quot;Fashion Style&quot;<br>        case .sportyChic: return &quot;Sporty Chic&quot;<br>        case .muaythaiTraining: return &quot;Muaythai Training&quot;<br>        case .backStretches: return &quot;Back Stretches&quot;<br>        case .boxingLifestyle: return &quot;Boxing Lifestyles&quot;<br>        case .shadowBoxing: return &quot;Shadow Boxing&quot;<br>        case .officeOutfit: return &quot;Office Outfit&quot;<br>        case .workwearStyle: return &quot;Workwear Style&quot;<br>        }<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209b84cfe396" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Unpopular Opinion — You Are Not Using Enough Lazy Variables]]></title>
            <link>https://medium.com/@emt.joshhart/swift-unpopular-opinion-you-are-not-using-enough-lazy-variables-258e84d2fa6d?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/258e84d2fa6d</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[lazy-var]]></category>
            <category><![CDATA[variables]]></category>
            <category><![CDATA[xcode]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Mon, 20 Mar 2023 04:24:53 GMT</pubDate>
            <atom:updated>2023-03-20T04:24:53.687Z</atom:updated>
            <content:encoded><![CDATA[<h3>Swift: Unpopular Opinion — You Are Not Using Enough Lazy Variables</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KWcsqePb6R7L9JnGqmcfvA.jpeg" /></figure><h3>GUILTY!</h3><p>When I first utilized a lazy variable, I was hooked! Since then, I’ve been slinging them all over my codebase, and for good reasons. You’re probably already aware of what a lazily initiated variable is. In case you don’t, let’s imagine something…sort of crazy…(lazy crazy, lol):</p><p>Who has ever done this? 😑</p><pre>private func setupTableView() {<br>    self.tableView.backgroundColor = .white<br>    self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;CustomCellId&quot;)<br>    self.tableView.delegate = self<br>    self.tableView.datasource = self<br>    self.tableView.estimatedRowHeight = UITableView.automaticDimension<br>    ....so on and so forth...<br>}</pre><p>The point of that code is to run the function once to set up your tableView on initialization; after that, you’re done with it…but it’s so much easier with a lazy variable, and it sort of reminds me of the code blocks you could execute on Interface Builder Outlets:</p><pre>private lazy var tableView: UITableView = {<br>    let table = UITableView(frame: self.view.bounds, style: .insetGrouped)<br>    table.backgroundColor = .white<br>    table.register(UITableViewCell.self, forCellReuseIdentifier: &quot;CustomCellId&quot;)<br>    table.delegate = self<br>    table.dataSource = self<br>    table.estimatedRowHeight = UITableView.automaticDimension<br>    table.separatorStyle = .none<br>    return table<br>}()</pre><p>It’s so helpful with tableViews because they are so expensive… and if you’re someone who has a UITabBarController with multiple tabs being initialized, you’ve probably seen this a few times in the debugger:</p><pre>UITableView was told to layout its visible cells and other contents <br>without being in the view hierarchy (the table view or one of its superviews <br>has not been added to a window)....blah blah blah</pre><p>The amazing thing about lazy variables is they don’t get pushed into memory until you need them, and they only get run one time because they are essentially a function.</p><p>Behind the scenes, if our lazy variable hasn’t been called, it’s sitting pretty and practically nil. When it does get called, it’s asked whether it’s called its setup function, and if not, calls it…so you could, and I do, imagine something like this happening behind the scenes:</p><pre><br>if tableView.hasNoValue {<br>   self.tableView = createTableView()<br>} else {<br>  return tableView<br>}<br><br>// There is more logic then this though.  It also will check which thread<br>// the lazy variable is being executed on and will handle synchronization<br>// typically involves locking or atomic operations.</pre><h3>Helps You Create Readable, Clean Code</h3><p>The main goal of clean, readable, functioning code is that everything is neatly organized and packaged. Your code is not only readable but predictable. My mother once told me the</p><blockquote>“most important rule of driving is being predictable”</blockquote><p>For me, it means that each aspect of my codebase follows a similar pattern. It means separating your code into digestible chunks and utilizing MARK and comments to inform the next lucky person to read it:</p><pre>// MARK: - ACTIONS:<br><br>/// When the value changes it changes the background color of the tableView.<br>/// - Parameter sender: (UISegmentedControl) The segmented control.<br>@IBAction private func valueChanged(_ sender: UISegmetedControl) {<br>  // Do stuff<br>}</pre><h3>Advantages:</h3><ol><li><strong>Improved performance:</strong> Lazy variables are only initialized when they are first accessed, meaning that unnecessary computation is avoided until absolutely necessary. This can lead to better app performance and faster startup times.</li><li><strong>Efficient memory usage:</strong> By only initializing resources when needed, lazy variables help reduce the memory footprint of an app, particularly when dealing with large or complex data structures.</li><li><strong>Resource optimization:</strong> Lazy variables can help optimize the use of system resources, such as CPU and memory, by only consuming them when required.</li><li><strong>Simplified initialization:</strong> Lazy variables can help simplify initialization code, as they can be used to initialize complex objects or perform expensive computations only when needed.</li><li><strong>Better separation of concerns:</strong> By using lazy variables, you can separate the initialization of an object from its usage, making the code more modular and easier to maintain.</li><li><strong>As-needed computation:</strong> Lazy variables allow for the execution of expensive or time-consuming operations only when the result is needed, preventing unnecessary processing.</li><li><strong>Avoiding circular dependencies:</strong> Lazy variables can help resolve circular dependencies between objects by deferring the initialization of one object until the other is ready.</li><li><strong>Enhanced code readability:</strong> Lazy variables make it clear which properties are expensive to compute, helping developers understand the code structure and identify potential performance bottlenecks.</li><li><strong>Easier error handling:</strong> By initializing resources only when needed, lazy variables make it easier to handle potential errors that may arise during initialization.</li><li><strong>Testability:</strong> Lazy variables make it easier to test code by allowing you to mock or stub the dependencies of the lazy property, leading to more effective and reliable tests.</li></ol><h3>Disadvantages:</h3><ol><li><strong>Checking initialization status:</strong> Each time a lazy variable is accessed, Swift needs to check if the variable has already been initialized. This requires additional processing to verify the initialization status, which adds a small overhead to each access.</li><li><strong>Synchronization:</strong> If a lazy variable is accessed from multiple threads, Swift employs synchronization mechanisms to prevent race conditions during the initialization. Synchronization typically involves locking or atomic operations, which can introduce additional overhead, especially in multi-threaded environments.</li><li><strong>Storage:</strong> Swift needs to store the initialization status of the lazy variable, typically using a hidden storage field or a flag. While this storage overhead is generally minimal, it does contribute to the overall overhead of using lazy variables.</li><li><strong>Function call overhead:</strong> When a lazy variable is initialized, Swift usually relies on a closure or function to perform the initialization. This introduces the overhead of a function call, which can be more significant for simple properties where the initialization itself is trivial.</li></ol><p><strong>But can we face the music here, the disadvantages of lazy variables, although noted, are VERY minimal.</strong></p><p>What do you think? Do you like them? Love them? Cannot live without them?</p><p>For those who have been developing with lazy variables what types of issues have you run into that would prevent you from using a lazy variable? For myself, I’ve used them across multiple production apps and have seen memory usage go way down. Leave your comments down below, and if you liked this article <strong>clap it, follow me</strong> (on Medium, not when I leave my driveway) and <strong>share it</strong> with a friend!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=258e84d2fa6d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: Creating A Background Task To Fetch Firebase Data (iOS 13+)]]></title>
            <link>https://medium.com/@emt.joshhart/swift-creating-background-task-to-fetch-firebase-data-ios-13-9a2c0c751c0d?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a2c0c751c0d</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[bgapprefresh]]></category>
            <category><![CDATA[background-task]]></category>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Fri, 24 Feb 2023 05:13:21 GMT</pubDate>
            <atom:updated>2023-07-28T02:30:57.163Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0x0npchmtSM_ssfwNUVldA.png" /><figcaption><strong>Morty the JR iOS Developer </strong>| The author generated this text in part with GPT-3. The author reviewed, edited, and revised and takes ultimate responsibility for the content of this publication.</figcaption></figure><p>Morty the junior iOS Developer was eager to learn how to run a background app refresh that would fetch posts from Firebase in Swift. He knew that this functionality would be essential for any app that needed to stay up to date and provide the latest information to its users.</p><p>Being a junior developer, Morty was still learning the ropes, but he was determined to get it right. He had heard that running a background app refresh was a tricky business, but he was ready to take on the challenge.</p><p>To get started, Morty did some research and discovered that in order to run a background app refresh in Swift, he needed to use the BackgroundTasks framework that was introduced in iOS 13. The BackgroundTasks framework provides a way for developers to schedule and run app refresh tasks in the background.</p><p><em>Morty began by updating his app to support iOS 15 or greater, which was necessary in order to use the latest features and frameworks. He then added the BackgroundTasks framework to his project and created a new task that would fetch posts from Firebase when the app was in the background.</em></p><p>To fetch posts from Firebase, Morty used the Firebase Realtime Database, which is a cloud-hosted database that stores and syncs data in real time. Morty implemented the Firebase Database API to fetch the posts and updated his app’s user interface accordingly.</p><p>Next, Morty had to determine when to schedule the background app refresh task. He decided that he would schedule it when the user backgrounded the app. He first edited his AppDelegate.swift file to include the necessary registration of the background task, and to schedule the background task:</p><pre>import UIKit<br>import FirebaseCore<br><br>@main<br>class AppDelegate: UIResponder, UIApplicationDelegate {<br><br>    // BACKGROUND TASK PROPERTIES:<br>    static let bgAppTaskId = &quot;your.background.task.identifier&quot;<br>    var bgTask: BGAppRefreshTask?<br>    lazy var bgExpirationHandler = {{<br>        if let task = self.bgTask {<br>            task.setTaskCompleted(success: true)<br>        }<br>    }}()<br><br>     func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -&gt; Bool {<br>        // Override point for customization after application launch.<br>        FirebaseApp.configure()<br>        registerBackgroundTask()<br>        return true<br>    }<br><br>    func applicationDidEnterBackground(_ application: UIApplication) {<br>        scheduleFirebasePostTask(minutes: 10) // We can set our intial request to anything we want.    <br>    }<br>}</pre><p>Also Morty made sure to add the identifier listed above (the <em>bgAppTaskId</em>) to his info.plist:</p><pre>&lt;key&gt;BGTaskSchedulerPermittedIdentifiers&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;string&gt;your.background.task.identifier&lt;/string&gt;<br>&lt;/array&gt;</pre><p>Add the background fetch &amp; background processing capabilities to your project: In your project settings, go to the &#39;Signing &amp; Capabilities&#39; tab, click on &#39;+ Capability&#39; and add &#39;Background Modes&#39;. Check the &#39;Background fetch&#39; &amp; ‘Background processing’ boxes.</p><p>Morty then created a new file to make sure that it was easy to find all the code related to background tasks in the future, he named it “AppDelegate+BackgroundTask.swift”:</p><pre>import BackgroundTasks<br><br>extension AppDelegate {<br><br>    // MARK - DEBUGGING BG TASK IN XCODE DEBUGGER:<br><br>    //////////////////////////////////////////////////////////////////<br>    // Simulate a background task:<br>    // Run the app, and after the app loads, use the XCode pause button<br>    // to pause the running of the app.<br>    // Copy the following into the XCode debugger:<br>    // e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@&quot;your.background.task.identifier&quot;]<br>    // Unpause app (you should now see the print statements from your background task being executed.<br><br>    // Simulate termination of a background task:<br>    // Make sure you have done the steps above.<br>    // Pause app<br>    // e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@&quot;your.background.task.identifier&quot;]<br>    // Unpause app<br>    //////////////////////////////////////////////////////////////////<br><br>    // MARK: - REGISTER OUR BG TASK:<br>    // When our App launches, register our task with Apple&#39;s task scheduler.<br>    // This must be done before &#39;applicationDidFinishLaunching(_:)&#39;<br><br>    /// We want to register our BG task for getting data from Firebase.<br>    /// - IMPORTANT: Needs to be called in &#39;didFinishLaunchingWithOptions&#39; App delegate function.<br>    func registerBackgroundTask() {<br>        BGTaskScheduler.shared.register(forTaskWithIdentifier: Self.bgAppTaskId, using: nil) { task in<br>            guard let firebaseTask = task as? BGAppRefreshTask else { return }<br>            self.bgTask = firebaseTask<br>            self.handleFirebasePostTask(firebaseTask)<br>        }<br>    }<br><br>    // MARK: - SCHEDULE OUR BG TASK:<br>    // When our App goes into the background, we need schedule when we want our task to be executed.<br>    // We must not overabuse &#39;how often&#39; we run our BG task as Apple could throttle it based on<br>    // how often our user actually uses our app.<br><br>    /// Schedule the app to try our background task for getting Firebase posts.<br>    /// - Parameter minutes: (Int) How many minutes from now do you want this to run?<br>    /// - IMPORTANT: Needs to be called in &#39;applicationDidEnterBackground&#39; App delegate function.<br>    func scheduleFirebasePostTask(minutes: Int) {<br>        do {<br>            let seconds = TimeInterval(minutes * 60)<br>            print(&quot;BG Task: Scheduling to run again in \(minutes) minutes.&quot;)<br>            let task = BGAppRefreshTaskRequest(identifier: Self.bgAppTaskId)<br>            task.earliestBeginDate = seconds == 0 ? nil : Date(timeIntervalSinceNow: seconds)<br>            try BGTaskScheduler.shared.submit(task)<br>        } catch {<br>            print(&quot;BG Task: Failed to submit to the BG Task Scheduler: \(error.localizedDescription)&quot;)<br>        }<br>    }<br><br>    // MARK: - HANDLE TASK:<br><br>    /// What our task will execute when it does get called.<br>    /// First we reschedule our app to run again in &#39;X&#39; minutes.<br>    /// We must set an expiration handler. (safety net)<br>    /// The handler gets called if our task is taking too long (for multiple reasons).<br>    /// Then we ask Firebase to give us fresh posts.<br>    /// - Parameter task: (BGAppRefreshTask) The task associated with getting firebase posts.<br>    private func handleFirebasePostTask(_ task: BGAppRefreshTask) {<br>        scheduleFirebasePostTask(minutes: 60) // This is how often we want our BG Task to run.<br>        task.expirationHandler = bgExpirationHandler<br>        getFirebasePosts(task)<br>    }<br><br>    // MARK: - GET FIREBASE POSTS:<br><br>    /// Will ask Firebase for new posts for our users.<br>    /// Whether the data is fetched successfully or not, we must set our task as completed once we get a response.<br>    /// If the network call for some reason hangs (poor network connection) the expiration handler on the task will be called.<br>    /// - Parameter task: (BGAppRefreshTask) The task associated with getting firebase posts.<br>    func getFirebasePosts(_ task: BGAppRefreshTask) {<br>        print(&quot;BG Task: Attempting to get Firebase Data.&quot;)<br><br>        let dispatchGroup = DispatchGroup()<br>        var fetchedDataSuccessfully = false<br><br>        dispatchGroup.enter()<br>        Fire.shared.getPosts(byPassCache: true) { results in<br>            switch results {<br>            case .success(let posts):<br>                fetchedDataSuccessfully = true<br>                print(&quot;BG Task: Firebase returned posts: \(posts)&quot;)<br>            case .failure(let error):<br>                fetchedDataSuccessfully = false<br>                print(&quot;BG Task: Firebase returned error: \(error.localizedDescription)&quot;)<br>            }<br>            dispatchGroup.leave()<br>        }<br><br>        dispatchGroup.notify(queue: .main) {<br>            print(&quot;BG Task: Finished getting Firebase Posts. Successful: \(fetchedDataSuccessfully)&quot;)<br>            task.setTaskCompleted(success: true)<br>        }<br>    }<br>}</pre><p>Once Morty had everything set up, he tested the app using some very helpful debugging code that he could input into the XCode debugging console and was thrilled to see that it was working perfectly. The app was able to run a background app refresh that fetched posts from Firebase, and it did so reliably and efficiently.</p><p>Morty was proud of his work and knew that his app was now better equipped to meet the needs of its users. He had learned a lot about implementing background app refresh functionality, and he was excited to use this knowledge in his future projects.</p><h3>Conclusion</h3><p>In conclusion, Morty the junior iOS Developer was able to learn how to run a background app refresh that fetched posts from Firebase in Swift. By using the BackgroundTasks framework, Morty was able to schedule and run app refresh tasks in the background, ensuring that the app’s data was always up to date. Morty’s determination and sense of humor paid off, and his app was now better equipped to provide the latest information to its users!</p><h3>Follow Me</h3><p>If you enjoyed reading this article and want to stay up-to-date with the latest tips and tricks for mastering Swift, then be sure to give me a follow! Not only will you gain access to my latest articles and tutorials, but you’ll also be treated to a daily dose of terrible puns and witty banter that will brighten up your day. So, what are you waiting for? Hit that follow and clap button and join the fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a2c0c751c0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Senior iOS Developers’ Secret: Creating Programmatic UI Quickly and Effortlessly]]></title>
            <link>https://medium.com/@emt.joshhart/senior-ios-developers-secret-creating-programmatic-ui-quickly-and-effortlessly-b8e400577cec?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8e400577cec</guid>
            <category><![CDATA[code-snippet]]></category>
            <category><![CDATA[programmatic-ui]]></category>
            <category><![CDATA[swift-secrets]]></category>
            <category><![CDATA[senior-ios-developer]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 22:14:33 GMT</pubDate>
            <atom:updated>2023-02-23T22:14:33.387Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vWE8rLh_XvpVy3GK" /><figcaption>Photo by <a href="https://unsplash.com/@sammywilliams?utm_source=medium&amp;utm_medium=referral">Sander Sammy</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Once upon a time, in a land far, far away, there was a junior iOS developer named Morty. Morty had just started his job at a new company, and he was excited to learn from the senior developers. However, there was one thing that had been puzzling him since day one: why, on earth, did the senior developers prefer programmatic user interfaces over the Interface Builder in Xcode, or even SwiftUI?</p><p>Morty had always thought that using the Interface Builder and SwiftUI was the best way to create user interfaces. It was easy, straightforward, and he could see the results right away. But the senior developers kept telling him that programmatic UI was the way to go, that it was more flexible, and that it allowed for better control over the app’s behavior, and scalability. Morty just didn’t get it.</p><p>One day, Morty decided to ask one of the senior developers, Jerry, why he preferred programmatic UI over storyboards and SwiftUI. Jerry looked at Morty and said, <strong>“Morty, my boy, programmatic UI is the way to go because it gives you complete control over the user interface. With programmatic UI, you can customize every aspect of the UI, and it’s much easier to manage large UIs.”</strong></p><p>Morty was still confused, but Jerry continued, <strong>“And, if you combine programmatic UI with code snippets, it’s even easier. Code snippets are reusable pieces of code that you can quickly insert into your projects, making it easy to create UI elements.” </strong>Jerry<strong> </strong>went on to explain how easy it was to create a TableViewController with programmatic UI utilizing a very untaught function called ‘loadView’. <strong>“With loadView you can quickly initialize your primary view before viewDidLoad even gets called.”</strong></p><p>Morty’s eyes widened as he realized what Jerry was saying. He had <em>heard</em> of code snippets before, but he had never thought of using them in combination with programmatic UI. Morty was even intrigued about this loadView function that Jerry referred to, what was it? Morty rushed back to his desk and started experimenting with programmatic UI, code snippets, and the loadView function:</p><pre>import UIKit<br><br>class MyTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {<br>    <br>    override func loadView() {<br>        self.view = tableView<br>    }<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .white<br>        self.title = &quot;Morty&#39;s Table View&quot;<br>    }<br><br>    lazy var tableView: UITableView = {<br>        let tableView = UITableView(frame: .zero, style: .plain)<br>        tableView.translatesAutoresizingMaskIntoConstraints = false<br>        tableView.delegate = self<br>        tableView.dataSource = self<br>        tableView.register(UITableViewCell.self, forCellReuseIdentifier: &quot;Cell&quot;)<br>        return tableView<br>    }()<br>    <br>    // MARK: - Table View Data Source<br>    <br>    func numberOfSections(in tableView: UITableView) -&gt; Int { 1 }<br>    <br>    func tableView(_ tableView: UITableView, <br>                     numberOfRowsInSection section: Int) -&gt; Int { 10 }<br>    <br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;Cell&quot;, for: indexPath)<br>        cell.textLabel?.text = &quot;Row \(indexPath.row + 1)&quot;<br>        return cell<br>    }<br>}</pre><p>To his surprise, Morty found that it was actually quite easy. With a few lines of Swift code, Morty created an entire table view controller in no time. He could customize every aspect of the UI, from the fonts and colors to the layout and animations. He even discovered that he could highlight the entire code of the view controller and right click on it to save it as a Code Snippet.</p><p>Morty discovered the secrecy of the loadView function:</p><blockquote>The loadView() function is a method provided by the UIViewController class in iOS development that is responsible for creating the view that the view controller manages. This function is called when the view controller&#39;s view property is accessed and its value is currently nil.</blockquote><blockquote>The default implementation of loadView() creates a view using Interface Builder, but you can override it to provide a custom view.</blockquote><blockquote>If you override loadView(), you are responsible for creating the view that the view controller manages, and setting it to the view controller&#39;s view property. You can create the view programmatically or load it from a nib file using the UINib class. When creating the view programmatically, you typically set up any subviews, constraints, and other properties that are needed to display the view properly.</blockquote><blockquote>It’s important to note that when overriding loadView(), you should not call the superclass implementation. Instead, you should create your own view and set it to the view property.</blockquote><p><strong>Morty was overjoyed.</strong> He had finally found the secret to creating amazing user interfaces with programmatic UI, code snippets and utilizing the loadView function. From that day on, Morty became a programmatic UI evangelist, and he shared his newfound knowledge with everyone he knew.</p><h3>Follow Me</h3><p>If you enjoyed reading this article and want to stay up-to-date with the latest tips and tricks for mastering Swift, then be sure to give me a follow! Not only will you gain access to my latest articles and tutorials, but you’ll also be treated to a daily dose of terrible puns and witty banter that will brighten up your day. So, what are you waiting for? Hit that follow and clap button and join the fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8e400577cec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What is type inference in Swift?]]></title>
            <link>https://medium.com/@emt.joshhart/what-is-type-inference-in-swift-294493095612?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/294493095612</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[type-inference]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Thu, 23 Feb 2023 21:40:06 GMT</pubDate>
            <atom:updated>2023-02-23T21:40:06.761Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KkLdNaX4pinIyG8zzy51JQ.png" /><figcaption><strong>Morty the JR iOS Developer</strong> | The author generated this text in part with GPT-3. The author reviewed, edited, and revised and takes ultimate responsibility for the content of this publication.</figcaption></figure><p>Morty is a junior iOS developer who has been working with Swift for a few months. While he is familiar with the basic syntax and concepts of the language, he has been hearing a lot about “<strong>type inference</strong>” lately and isn’t quite sure what it means. In this article, we’ll explore type inference in Swift and give some coding examples to help Morty understand it better.</p><p>Type inference is a feature of Swift that allows the compiler to automatically determine the type of a variable or constant based on its initial value. This means that you don’t have to explicitly declare the type of a variable or constant, which can save you some typing and make your code more concise.</p><p>Let’s take a look at an example. Suppose we want to create a variable called “message” and assign it the value “Hello, World!”.</p><pre>var message = &quot;Hello, World!&quot;</pre><p>In this case, we didn’t have to specify the type of the variable “message” because Swift was able to infer it from the initial value. Since the initial value is a string, Swift knows that “message” should be a string as well.</p><p>Now let’s look at another example. Suppose we want to create a variable called “count” and assign it the value 42.</p><pre>var count = 42</pre><p>In this case, Swift is able to infer that “count” should be an integer because the initial value is an integer. We didn’t have to explicitly declare it as an integer.</p><p>Type inference can also be used with function parameters and return values. For example, suppose we want to write a function that takes in a string and returns the length of the string.</p><pre>func getLength(str: String) -&gt; Int { str.count }</pre><p>In this function, we didn’t have to specify the type of the “str” parameter because Swift was able to infer that it should be a string based on the function signature. Similarly, we didn’t have to specify the return type of the function because Swift was able to infer that it should be an integer based on the return statement.</p><p>Type inference can be a powerful tool for writing concise and readable Swift code. However, it’s important to keep in mind that it’s not always appropriate to rely on type inference. In some cases, explicitly declaring the type of a variable or function parameter can make your code more clear and less error-prone.</p><h3>Conclusion</h3><p>In conclusion, type inference is a feature of Swift that allows the compiler to automatically determine the type of a variable or constant based on its initial value. This can save you some typing and make your code more concise, but it’s important to use it judiciously. By understanding type inference, Morty and other iOS developers can write cleaner and more efficient code in Swift.</p><h3>Follow Me</h3><p>If you enjoyed reading this article and want to stay up-to-date with the latest tips and tricks for mastering Swift, then be sure to give me a follow. Not only will you gain access to my latest articles and tutorials, but you’ll also be treated to a daily dose of terrible puns and witty banter that will brighten up your day. So, what are you waiting for? Hit that follow and clap button and join the fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=294493095612" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Collections High-Order Functions Cheat Sheet]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://medium.com/@emt.joshhart/swift-collections-high-order-functions-cheat-sheet-65fbb05e82e4?source=rss-7dfdfde67f1b------2"><img src="https://cdn-images-1.medium.com/max/2600/1*6id3ZwbDnSZs3Eiai_vUVA.png" width="13659"></a></p><p class="medium-feed-link"><a href="https://medium.com/@emt.joshhart/swift-collections-high-order-functions-cheat-sheet-65fbb05e82e4?source=rss-7dfdfde67f1b------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://medium.com/@emt.joshhart/swift-collections-high-order-functions-cheat-sheet-65fbb05e82e4?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/65fbb05e82e4</guid>
            <category><![CDATA[cheatsheet]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[high-order-functions]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Tue, 21 Feb 2023 05:47:48 GMT</pubDate>
            <atom:updated>2023-07-29T05:37:18.340Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[Error Domain=NSItemProviderErrorDomain Code=-1000 “Cannot load representation of type public.jpeg”]]></title>
            <link>https://medium.com/@emt.joshhart/error-domain-nsitemprovidererrordomain-code-1000-cannot-load-representation-of-type-public-jpeg-127b94e1bd28?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/127b94e1bd28</guid>
            <category><![CDATA[cannot-load]]></category>
            <category><![CDATA[nsitemprovider]]></category>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 01:42:54 GMT</pubDate>
            <atom:updated>2023-02-18T01:42:54.855Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvGPxCIXvERmPBxEECoPNg.png" /><figcaption><em>The author generated this text in part with GPT-3. The author reviewed, edited, and revised and takes ultimate responsibility for the content of this publication.</em></figcaption></figure><p>As a junior iOS developer, it’s not uncommon to run into errors and issues while working on your app. One such error that you may encounter is “Error Domain=NSItemProviderErrorDomain Code=-1000 ‘Cannot load representation of type public.jpeg’”. This error typically occurs when your app is attempting to load a JPEG file using an NSItemProvider but is unable to do so for some reason.</p><p>Let’s take the example of Morty, a junior iOS developer who is working on an app that involves displaying JPEG images. While testing his app, Morty encounters this error, and he’s not sure how to resolve it.</p><p>The error message indicates that the app is unable to load the representation of the public.jpeg type, with additional information indicating that the file couldn’t be opened. Morty may be feeling confused and frustrated at this point, but there are several steps he can take to resolve the error.</p><h3>Check the file path</h3><p>The first thing Morty should do is check the file path to ensure that it is correct and that the file exists at that location. He can do this by navigating to the location in Finder and checking if the file is present. If the file is not there, he may need to add it to the project or move it to the correct location.</p><p>If the image is one of the default images on the iOS Simulator, Morty can still verify the file path by following these steps:</p><ol><li><em>In Xcode, navigate to the file that is giving the error.</em></li></ol><p><em>2. Check the file name and file extension. If the file is a default image on the iOS Simulator, Morty can use the filename to identify the file.</em></p><p><em>3. In Finder, navigate to the location where the default images are stored on the iOS Simulator. The default images are stored in the Simulator’s app container in the file system.</em></p><p><em>4. To access the file system, Morty can open the iOS Simulator by selecting “Open Developer Tool” from the Xcode menu and then selecting “Simulator”. Once the iOS Simulator opens, he can select “File” from the menu bar and then select “Open Device” to access the Simulator’s file system.</em></p><p><em>5. Once Morty has access to the file system, he can navigate to the location where the default images are stored. The default images are usually stored in the “Library” directory in the app container.</em></p><p><em>6. Verify that the default image is present at the location specified in Xcode.</em></p><p><em>7. If the default image is present, Morty can compare the file path displayed in Finder with the file path in Xcode. If the file path in Xcode is incorrect, Morty will need to update the file path in Xcode to match the correct location of the default image on the iOS Simulator.</em></p><p>By following these steps, Morty can verify the file path for a default image on the iOS Simulator and resolve any issues related to the file path.</p><h3>Check the file permissions</h3><p>If Morty confirms that the file exists and is in the correct location, the next thing he should check is whether his app has the necessary permissions to access the file. He can do this by checking the file permissions in Finder or in Xcode.</p><h3>Verify the file format</h3><p>Another possible cause of the error is that the file is not in the correct format. Morty should double-check that the file is actually a JPEG file and that it hasn’t been corrupted or modified in some way.</p><h3>Check for missing frameworks</h3><p>Morty may also need to check whether he has included the appropriate frameworks for handling JPEG files in his Xcode project.</p><p>By following these steps, Morty can likely resolve the error and continue working on his app. If he still cannot resolve the error, he can seek additional help from the Xcode community or Apple Support.</p><h3>Conclusion</h3><p>As a junior iOS developer, encountering errors like this can be frustrating, but it’s important to remember that they are a natural part of the development process. By staying patient and persistent, and using resources like the Xcode community and Apple Support, Morty can overcome this error and continue to grow as a developer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=127b94e1bd28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solve “secTaskDiagnoseEntitlements Missing Keychain Entitlements: No Stored taskRef found” Swift…]]></title>
            <link>https://medium.com/@emt.joshhart/solve-sectaskdiagnoseentitlements-missing-keychain-entitlements-no-stored-taskref-found-swift-d10b8bc47227?source=rss-7dfdfde67f1b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d10b8bc47227</guid>
            <category><![CDATA[keychain]]></category>
            <category><![CDATA[error]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[securityframework]]></category>
            <category><![CDATA[xcode]]></category>
            <dc:creator><![CDATA[Joshua Hart]]></dc:creator>
            <pubDate>Sat, 18 Feb 2023 01:00:55 GMT</pubDate>
            <atom:updated>2023-02-18T01:43:26.592Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0x0npchmtSM_ssfwNUVldA.png" /><figcaption>The author generated this text in part with GPT-3. The author reviewed, edited, and revised and takes ultimate responsibility for the content of this publication.</figcaption></figure><h3>Solve “secTaskDiagnoseEntitlements Missing Keychain Entitlements: No Stored taskRef found” Swift Error</h3><p>This error message suggests that there is a problem with the keychain entitlements for a security task in an application. Specifically, it indicates that the security task is missing a required entitlement for accessing the keychain, (<em>which is a secure storage system for passwords and other sensitive information on macOS and iOS</em>).</p><p>The message suggests that the security task is unable to find a stored reference to a keychain entitlement, which may indicate that the application has not been properly configured to <strong>use the keychain</strong> or that there is a problem with the way the security task is <strong>accessing the keychain</strong>. It could also indicate that the <strong>keychain has become corrupted</strong> or <strong>contains invalid items</strong>, or that your <strong>app or the OS of the device is outdated or incompatible</strong> with each other.</p><p>To resolve this issue, you may need to review the code for the application to ensure that it is <strong>properly configured</strong> to use the keychain, and that the <strong>necessary entitlements are included</strong> in the application’s entitlements file. It may also be necessary to review the code for the security task to ensure that it is <strong>properly accessing the keychain</strong> and any required entitlements.</p><p>There are different types of keychain entitlements that an application may require, depending on its specific needs. Here are some common keychain entitlements that an application may need:</p><p><strong>kSecEntitlementKeychainAccess</strong> — <em>Grants the app permission to access the keychain. Without this entitlement, the application will not be able to access the keychain.</em></p><p><strong>kSecEntitlementKeychainShare</strong> —<em> Allows the app to share keychain items with other apps. This can be useful if multiple applications need to access the same keychain items.</em></p><p><strong>kSecEntitlementKeychainPrompt</strong> — <em>Allows the application to prompt the user for permission to access the keychain. This can be useful for apps that need to access sensitive information in the keychain.</em></p><p><strong>kSecEntitlementKeychainDelete</strong> — <em>Allows the app to delete items from the keychain. Without this entitlement, the application will not be able to remove items from the keychain.</em></p><p><strong>kSecEntitlementKeychainSync</strong> — <em>Allows the app to synchronize keychain items with iCloud. This can be useful for applications that need to share keychain items across multiple devices.</em></p><h3>Conclusion</h3><p>It’s important to note that not all applications require all of these entitlements, and the specific entitlements needed will depend on the application’s requirements. The entitlements must be specified in the application’s entitlements file, which is included in the application bundle.</p><h3>Help Me</h3><p>If you enjoyed reading this article and want to stay up-to-date with the latest tips and tricks for mastering Swift, then be sure to give me a follow! Not only will you gain access to my latest articles and tutorials, but you’ll also be treated to a daily dose of terrible puns and witty banter that will brighten up your day. So, what are you waiting for? Hit that follow and clap button and join the fun!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d10b8bc47227" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>