<?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 Cyril Vasilyev on Medium]]></title>
        <description><![CDATA[Stories by Cyril Vasilyev on Medium]]></description>
        <link>https://medium.com/@quazilier?source=rss-2b897fdd696c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*5rZucYQWmAZ3XKgI</url>
            <title>Stories by Cyril Vasilyev on Medium</title>
            <link>https://medium.com/@quazilier?source=rss-2b897fdd696c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 19:13:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quazilier/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[Crafting the Ultimate Custom Tab Bar for Lastfloors]]></title>
            <link>https://medium.com/@quazilier/crafting-the-ultimate-custom-tab-bar-for-lastfloors-008320f21433?source=rss-2b897fdd696c------2</link>
            <guid isPermaLink="false">https://medium.com/p/008320f21433</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[rxswift]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Cyril Vasilyev]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 16:26:41 GMT</pubDate>
            <atom:updated>2024-09-15T08:28:12.862Z</atom:updated>
            <content:encoded><![CDATA[<p>At <strong>Lastfloors</strong>, we decided that the standard UITabBarController was as thrilling as watching paint dry on a rainy Sunday. We craved something special for our tab bar. So, we embarked on a quest to create the ultimate custom tab bar with a unique shape, a standout middle button, and clever tap handling—all while gracefully avoiding the pitfalls of a fully custom tab bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IB8jqaFdQHBn07a_DwrgHw.png" /></figure><h3>Why Settle for Ordinary?</h3><p>Let’s face it, default tab bars are the plain oatmeal of UI components — nutritious but hardly thrilling. We wanted our app to have a tab bar that’s more like a stack of pancakes drizzled with maple syrup and topped with fresh berries — delightfully engaging and memorable. So, we set out to build a custom tab bar with a unique shape, an eye-catching middle button, and some clever tricks up our sleeves to keep things efficient and maintainable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EBU7w6ePHMjJe2UGhMe3vQ.gif" /></figure><h3>The Masterpiece</h3><p>Behold, the pièce de résistance of our endeavor — the LastfloorsTabBarController.swift file. We&#39;ll walk through this code like a guided tour through an art museum, except with more code and fewer pretentious whispers.</p><pre>import UIKit<br>import RxSwift<br>import RxCocoa<br><br>final class LastfloorsTabBarController: UITabBarController {<br> var sessionManager: UserSessionManager<br> private let disposeBag = DisposeBag()<br> private let middleTabSubject = PublishSubject&lt;Void&gt;()<br><br>private let iconSize = CGSize(width: 31, height: 31)<br> private var imageView: UIImageView?<br><br>private var imageViewWidthConstraint: NSLayoutConstraint?<br> private var imageViewHeightConstraint: NSLayoutConstraint?<br><br>private lazy var middleCircleView: UIView = {<br> let view = UIView(frame: CGRect(x: 0, y: 0, width: 62, height: 62))<br> view.backgroundColor = UIColor.alfTabBarMainColor<br> view.layer.cornerRadius = 31<br> setupMiddleCircleIcon(in: view)<br> return view<br> }()<br><br>init(sessionManager: UserSessionManager) {<br> self.sessionManager = sessionManager<br> super.init(nibName: nil, bundle: nil)<br> }<br><br>required init?(coder aDecoder: NSCoder) {<br> fatalError(&quot;init(coder:) has not been implemented&quot;)<br> }</pre><h3>Breaking It Down</h3><ul><li><strong>Imports</strong>: We import UIKit, RxSwift, and RxCocoa because we&#39;re embracing reactive programming for dynamic element.</li><li><strong>Class Declaration</strong>: Our class is final because we want to prevent subclassing—this tab bar controller is perfect as is!</li><li><strong>Properties</strong>:</li><li>sessionManager: Manages user sessions and decides which screen to presen.</li><li>disposeBag and middleTabSubject: For handling RxSwift subscriptions, because memory leaks are like uninvited guests—they overstay their welcome.</li><li>iconSize: The size of our middle icon, chosen with the precision of a Swiss watchmaker.</li><li>imageView: Holds the icon image.</li><li>imageViewWidthConstraint and imageViewHeightConstraint: Constraints to adjust the icon size during animations.</li><li>middleCircleView: Our custom middle button, which we&#39;ll discuss in detail.</li></ul><h3>Initializers</h3><p>We have a custom initializer because we’re not using storyboards — storyboards are so last decade.</p><pre>init(sessionManager: UserSessionManager) {<br> self.sessionManager = sessionManager<br> super.init(nibName: nil, bundle: nil)<br>}<br><br>required init?(coder aDecoder: NSCoder) {<br> fatalError(&quot;init(coder:) has not been implemented&quot;)<br>}</pre><ul><li>We initialize with a sessionManager.</li><li>We throw a fatal error if someone tries to use the storyboard initializer because we prefer code-based layouts.</li></ul><h3>viewDidLoad: Setting Up the Party</h3><p>In viewDidLoad, we configure our view controllers, set up the middle circle view, select the default tab, and set up observers.</p><pre>override func viewDidLoad() {<br> super.viewDidLoad()<br> configureViewControllers()<br> setupMiddleCircleView()<br> self.selectedIndex = 2<br> setupMiddleTabObserver()<br>}</pre><ul><li><strong>configureViewControllers()</strong>: Sets up the tabs.</li><li><strong>setupMiddleCircleView()</strong>: Prepares our custom middle button.</li><li><strong>selectedIndex = 2</strong>: Defaults to the middle tab because it&#39;s the star of the show.</li><li><strong>setupMiddleTabObserver()</strong>: Sets up an observer for taps on the middle button.</li></ul><h3>loadView: Adding Our Custom Views</h3><pre>override func loadView() {<br>    super.loadView()<br>    self.tabBar.addSubview(middleCircleView)<br>    setupCustomTabBar()<br>}</pre><p>We override loadView to add our middleCircleView to the tab bar and set up our custom tab bar shape.</p><h3>viewDidLayoutSubviews: Keeping Things Fresh</h3><pre>override func viewDidLayoutSubviews() {<br>    super.viewDidLayoutSubviews()<br>    removeExistingTabBarShape()<br>    setupCustomTabBar()<br>}</pre><p>We ensure our custom tab bar shape is redrawn whenever the layout changes because a stale UI is like week-old bread — nobody wants it.</p><h3>Step-by-Step Breakdown</h3><h3>1. Setting Up the Middle Circle Icon</h3><p>Our middle circle button needs an icon to show off.</p><pre>private func setupMiddleCircleIcon(in view: UIView) {<br>    if let originalIcon = UIImage(systemName: &quot;aqi.medium&quot;) {<br>        let imageView = UIImageView(image: originalIcon.withRenderingMode(.alwaysTemplate))<br>        imageView.tintColor = .alfButtonText<br>        imageView.contentMode = .scaleAspectFit<br>        imageView.translatesAutoresizingMaskIntoConstraints = false<br>        view.addSubview(imageView)<br>        self.imageView = imageView<br><br>        NSLayoutConstraint.activate([<br>            imageView.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            imageView.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>        ])<br><br>        imageViewWidthConstraint = imageView.widthAnchor.constraint(equalToConstant: iconSize.width)<br>        imageViewHeightConstraint = imageView.heightAnchor.constraint(equalToConstant: iconSize.height)<br>        imageViewWidthConstraint?.isActive = true<br>        imageViewHeightConstraint?.isActive = true<br>    }<br>}</pre><ul><li>We use a system image named &quot;aqi.medium&quot; because it looks sleek and modern.</li><li>We set up the image view with contentMode set to .scaleAspectFit to handle resizing.</li><li>We store the width and height constraints in properties so we can update them during animations.</li><li>We add the image to our middleCircleView and center it using Auto Layout.</li></ul><h3>2. Positioning the Middle Circle View</h3><pre>private func setupMiddleCircleView() {<br>    middleCircleView.frame = CGRect(<br>        x: (self.tabBar.bounds.width / 2) - 31,<br>        y: -10,<br>        width: 62,<br>        height: 62<br>    )<br>    let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleMiddleCircleTap))<br>    middleCircleView.addGestureRecognizer(tapGesture)<br>}</pre><ul><li>We center the middleCircleView horizontally and place it slightly above the tab bar for that &quot;popping out&quot; effect.</li><li>We add a tap gesture recognizer because our middle button wants to interact with the user.</li></ul><h3>Special Feature: Transparent Taps and Reactive Listening</h3><p>Instead of relying on the default tab bar item behavior, <strong>we directly handle the tap events on the </strong><strong>middleCircleView</strong> by adding a UITapGestureRecognizer to it. This means when a user taps the middle circle, <strong>the tap is captured directly by the circle itself</strong>, not passed through to the underlying tab bar item. The circle responds immediately, and we use <strong>RxSwift </strong>to reactively handle this interaction.</p><h4>Why is this graceful?</h4><ul><li><strong>Simplicity</strong>: We didn’t need to create a fully custom tab bar from scratch, which can be as tricky as assembling IKEA furniture without instructions.</li><li><strong>Maintainability</strong>: By leveraging the existing UITabBarController functionality, we keep our code clean, modular, and easy to maintain. The middle circle is simply an overlay on the tab bar, so we can manage interactions independently.</li><li><strong>Elegance</strong>: The middle circle appears as a special element, but the underlying tab bar item is still there (though disabled) for consistent behavior. It allows us to handle the interaction cleanly, without disrupting the tab bar’s standard behavior.</li></ul><h4>How does this work?</h4><p>We add a <strong>tap gesture recognizer</strong> to the middleCircleView itself and <strong>disable</strong> the middle tab bar item (isEnabled = false). When the circle is tapped, <strong>RxSwift</strong> captures the event, and we reactively update the UI by changing the selected index and animating the middle circle view. This way, the middle tab behaves like the other tabs but with its own custom flair.</p><h3>3. Removing Existing Tab Bar Shapes</h3><p>Before we redraw our custom tab bar, we need to clean up any existing shapes to prevent layering issues.</p><pre>private func removeExistingTabBarShape() {<br>    self.tabBar.layer.sublayers?.forEach {<br>        if $0 is CAShapeLayer {<br>            $0.removeFromSuperlayer()<br>        }<br>    }<br>}</pre><ul><li>We loop through the tab bar’s sublayers and remove any CAShapeLayer instances.</li></ul><h3>4. Setting Up the Custom Tab Bar</h3><p>Now, let’s get artistic with our Bezier path.</p><pre>private func setupCustomTabBar() {<br>    let path: UIBezierPath = getPathForTabBar()<br>    let shape = CAShapeLayer()<br>    shape.path = path.cgPath<br>    shape.lineWidth = 3<br>    shape.strokeColor = UIColor.clear.cgColor<br>    shape.fillColor = UIColor.alfTabBarBackground.cgColor<br>    self.tabBar.layer.insertSublayer(shape, at: 0)<br>    self.tabBar.itemWidth = 40<br>    self.tabBar.itemPositioning = .centered<br>    self.tabBar.itemSpacing = 180<br><br>    self.tabBar.tintColor = .alfTabBarMainColor<br><br>    self.tabBar.backgroundColor = .clear<br>    self.tabBar.backgroundImage = UIImage()<br>    self.tabBar.shadowImage = UIImage()<br>}</pre><ul><li>We create a CAShapeLayer with the path from getPathForTabBar().</li><li>We style the tab bar to remove the default background and shadows.</li><li>We set the item width and spacing to align our tab bar items properly.</li></ul><h3>5. Crafting the Bezier Path</h3><p>Here’s where we unleash our inner Michelangelo.</p><pre>private func getPathForTabBar() -&gt; UIBezierPath {<br>    let frameWidth = self.tabBar.bounds.width<br>    let frameHeight = self.tabBar.bounds.height + 20<br>    let holeWidth = 150<br>    let holeHeight = 75<br>    let leftXUntilHole = Int(frameWidth / 2) - Int(holeWidth / 2)<br><br>    let path = UIBezierPath()<br>    path.move(to: CGPoint(x: 0, y: 0))<br>    path.addLine(to: CGPoint(x: leftXUntilHole, y: 0))<br>    path.addCurve(<br>        to: CGPoint(x: leftXUntilHole + (holeWidth / 3), y: holeHeight / 2),<br>        controlPoint1: CGPoint(x: leftXUntilHole + ((holeWidth / 3) / 8) * 6, y: 0),<br>        controlPoint2: CGPoint(x: leftXUntilHole + ((holeWidth / 3) / 8) * 8, y: holeHeight / 2)<br>    )<br>    path.addCurve(<br>        to: CGPoint(x: leftXUntilHole + (2 * holeWidth) / 3, y: holeHeight / 2),<br>        controlPoint1: CGPoint(<br>            x: leftXUntilHole + (holeWidth / 3) + (holeWidth / 3) / 3 * 2 / 5,<br>            y: (holeHeight / 2) * 6 / 4<br>        ),<br>        controlPoint2: CGPoint(<br>            x: leftXUntilHole + (holeWidth / 3) + (holeWidth / 3) / 3 * 2 + (holeWidth / 3) / 3 * 3 / 5,<br>            y: (holeHeight / 2) * 6 / 4<br>        )<br>    )<br>    path.addCurve(<br>        to: CGPoint(x: leftXUntilHole + holeWidth, y: 0),<br>        controlPoint1: CGPoint(x: leftXUntilHole + (2 * holeWidth) / 3, y: holeHeight / 2),<br>        controlPoint2: CGPoint(x: leftXUntilHole + (2 * holeWidth) / 3 + (holeWidth / 3) * 2 / 8, y: 0)<br>    )<br>    path.addLine(to: CGPoint(x: frameWidth, y: 0))<br>    path.addLine(to: CGPoint(x: frameWidth, y: frameHeight))<br>    path.addLine(to: CGPoint(x: 0, y: frameHeight))<br>    path.addLine(to: CGPoint(x: 0, y: 0))<br>    path.close()<br>    return path<br>}</pre><ul><li>We calculate dimensions for the tab bar and the “hole” where our circle button sits.</li><li>We move and add lines and curves to create a custom shape.</li><li>The Bezier path creates a concave curve in the middle of the tab bar to accommodate our circle.</li></ul><h3>6. Handling Middle Circle Taps</h3><p>Our middle button isn’t just for show — it needs to respond to user interaction.</p><pre>@objc private func handleMiddleCircleTap() {<br>    middleTabSubject.onNext(())<br>}</pre><ul><li>When the middle circle is tapped, we emit an event through middleTabSubject.</li></ul><p><strong>But here’s the twist:</strong> Since our circle is <strong>transparent to taps</strong>, the tap event actually goes to the underlying tab bar item — the middle one with no icon or label. This is how we cleverly avoid fully customizing the tab bar.</p><h3>7. Observing Middle Tab Taps</h3><p>We use RxSwift to observe taps on the middle circle and perform actions accordingly.</p><pre>private func setupMiddleTabObserver() {<br>    middleTabSubject<br>        .subscribe(onNext: { [weak self] in<br>            guard let self = self else { return }<br>            self.animateMiddleCircleViewSelection(isSelected: true)<br>            self.selectedIndex = 2<br>        })<br>        .disposed(by: disposeBag)<br>}</pre><ul><li><strong>We increment a tap count each time the middle circle is tapped.</strong> (Psst! This increment is for calling an <strong>Easter egg</strong>, but more on that next time!)</li><li>We animate the middle circle to indicate selection and set the selected index to 2.</li></ul><p>Our tap count isn’t just for show; it’s part of a hidden feature. But shhh — it’s a secret for now!</p><h3>8. Animating the Middle Circle</h3><p>What’s better than a static button? An animated one!</p><pre>private func animateMiddleCircleViewSelection(isSelected: Bool) {<br>    let newSize: CGFloat = isSelected ? 64 : 60<br>    let newIconSize = CGSize(width: newSize * 0.5, height: newSize * 0.5)<br>    let newCornerRadius: CGFloat = newSize / 2<br>    let newX = (self.tabBar.bounds.width / 2) - (newSize / 2)<br>    let newY: CGFloat = isSelected ? -10 : -5<br>    let newColor: UIColor = isSelected ? UIColor.alfTabBarMainColor : UIColor.alfMainColorDeselect<br><br>    UIView.animate(withDuration: 0.3, animations: {<br>        self.middleCircleView.frame = CGRect(x: newX, y: newY, width: newSize, height: newSize)<br>        self.middleCircleView.layer.cornerRadius = newCornerRadius<br>        self.middleCircleView.backgroundColor = newColor<br><br>        self.imageViewWidthConstraint?.constant = newIconSize.width<br>        self.imageViewHeightConstraint?.constant = newIconSize.height<br><br>        self.middleCircleView.layoutIfNeeded()<br>    })<br>}</pre><ul><li>We adjust the size, position, corner radius, and background color based on the selection state.</li><li>We update the imageViewWidthConstraint and imageViewHeightConstraint to resize the icon smoothly.</li><li>We animate these changes for a smooth transition.</li></ul><h3>9. Configuring View Controllers</h3><p>Now, let’s set up the actual tabs for our tab bar.</p><pre>private func configureViewControllers() {<br>// Some other ViewControllers<br><br>    let dashboardVC = DashboardParentVC()<br>    let dashboardNavVC = UINavigationController(rootViewController: dashboardVC)<br>    dashboardNavVC.tabBarItem = UITabBarItem(title: &quot;&quot;, image: UIImage(), tag: 2)<br>    dashboardNavVC.tabBarItem.isEnabled = false<br><br>// More ViewControllers<br><br>    viewControllers = [<br>// Some other ViewControllers<br>        dashboardNavVC,<br>// More ViewControllers<br>    ]<br>}</pre><ul><li>We create five tabs, each with its own view controller.</li><li>The middle tab (dashboardNavVC) is our special tab with an empty title and image, and we disable it to prevent default behavior.</li><li>By disabling the middle tab bar item’s interaction (isEnabled = false), we ensure that taps on the circle don&#39;t trigger the default tab bar item selection. Instead, we handle it ourselves, making the circle appear interactive without the complexity of a fully custom tab bar.</li></ul><h3>10. Handling Tab Bar Item Selection</h3><p>We override the tabBar(_:didSelect:) method to animate our middle circle when needed.</p><pre>override func tabBar(_ tabBar: UITabBar, didSelect item: UITabBarItem) {<br>    animateMiddleCircleViewSelection(isSelected: item.tag == 2)<br>}</pre><ul><li>If the selected tab is the middle one (tag 2), we animate the circle to show it’s selected.</li><li>Otherwise, we animate it to the unselected state.</li></ul><h3>Conclusion: The Result of Our Creative Ingenuity</h3><p>At <strong>Lastfloors</strong>, we wanted something special for the tab bar — something that not only functioned well but also stood out like a flamingo in a flock of pigeons. By cleverly making our circle transparent to taps and listening reactively to the tab bar button (which has no icon or label), we gracefully sidestepped the need to fully customize the tab bar. This approach keeps our code maintainable, leverages the strengths of UITabBarController, and gives our users a delightful experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=008320f21433" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating the SensorView Component]]></title>
            <link>https://medium.com/@quazilier/creating-the-sensorview-component-3709939bf696?source=rss-2b897fdd696c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3709939bf696</guid>
            <category><![CDATA[ui-kit-design]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Cyril Vasilyev]]></dc:creator>
            <pubDate>Sun, 20 Aug 2023 14:06:43 GMT</pubDate>
            <atom:updated>2023-08-21T13:23:32.960Z</atom:updated>
            <content:encoded><![CDATA[<p>When I was working on my latest project, I was faced with the task of creating a user-friendly and intuitive interface to display data from physical sensors analyzing air quality. In this article, I’ll use “Air Quality” and “UV Index” as examples. The idea is that this component would allow switching between different values to display various parameters on the map markers. I named this component SensorView. Below I&#39;ll share the full code of the component, but I also provide a link <a href="https://github.com/Bazilier/componentview">to the project&#39;s repository</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*X51nVdBl3yzWKSe3jdY-WQ.gif" /></figure><p>I needed something similar to a context menu, but the specifications required that the options do not appear in a separate native view. It was meant to function like this: when a button is pressed, it expands downwards, offering an option to select a parameter or click an info button labeled “What is this”.</p><p>In this article, I’ll show how I created this component view using UIKit in code without relying on Storyboards. Here are the components I used:</p><h3>Variables:</h3><ul><li>Size Constants: Here, we define the sizes that we’ll use for positioning and styling our interface elements.</li><li>Primary and Secondary UIStackView: These elements are used for grouping and vertically positioning buttons. Stacks were convenient because when a button’s .isHidden = true (meaning the button is hidden), the StackView automatically collapses.</li><li>Buttons: Here we create the main button, which displays the current parameter and is also responsible for activating the menu, a button to display air quality, a button for the UV Index, an information button, and a round button to display an icon of the current parameter. Currently, it doesn’t handle events.</li></ul><h3>Functions:</h3><ul><li>setupViews(): This function is responsible for adding all the interface elements to the main view and their basic setup.</li><li>setupConstraints(): Here, we set constraints for all the interface elements, determining their position and sizes relative to each other and the main view.</li><li>createButton(...): This is a generic function to create buttons with various properties, avoiding code duplication for each new button.</li></ul><h3>Event Handling:</h3><ul><li>Main Button Press: The mainButtonTapped() function is triggered when the main button is pressed, leading to the menu either expanding or collapsing.</li><li>Air Quality Button Press: The airQualityButtonTapped() function is activated when the user selects the &quot;Air Quality&quot; parameter.</li><li>UV Index Button Press: The uvIndexButtonTapped() function is triggered when the &quot;UV Index&quot; parameter is selected.</li></ul><p>Here is the code for this component with my comments:</p><pre>import UIKit<br>import SnapKit<br><br>// Enumeration to determine the current parameter<br>enum Parameter {<br>    case airQuality<br>    case uvIndex<br>}<br><br>// Main sensor view class<br>class SensorView: UIView {<br>    <br>    // Structure for determining layout sizes and constants<br>    struct Layout {<br>        static let screenWidth = UIScreen.main.bounds.width<br>    }<br>    <br>    // Currently selected parameter<br>    var currentParameter: Parameter = .airQuality<br>    <br>    // Primary vertical stack view<br>    let primaryStackView: UIStackView = {<br>        let stack = UIStackView()<br>        stack.backgroundColor = .white<br>        stack.axis = .vertical<br>        stack.layer.cornerRadius = 26<br>        let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15)<br>        stack.layoutMargins = insets<br>        stack.isLayoutMarginsRelativeArrangement = true<br>        <br>        return stack<br>    }()<br>    <br>    // Secondary vertical stack view<br>    let secondaryStackView: UIStackView = {<br>        let stack = UIStackView()<br>        stack.backgroundColor = .white<br>        stack.axis = .vertical<br>        let insets = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)<br>        stack.layoutMargins = insets<br>        stack.isLayoutMarginsRelativeArrangement = true<br>        return stack<br>    }()<br>    <br>    // Main button displaying the current parameter<br>    private lazy var mainButton: UIButton = {<br>        let button: UIButton = createButton(title: &quot;Air Quality&quot;.uppercased(), action: #selector(mainButtonTapped), height: 58, target: self)<br>        button.setImage(UIImage.init(systemName: &quot;chevron.down&quot;), for: .normal)<br>        button.contentHorizontalAlignment = .left<br>        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: -10)<br>        button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 40, bottom: 0, right: 0)<br>        return button<br>    }()<br>    <br>    // Button to select air quality<br>    private lazy var airQualityButton: UIButton = {<br>        let button = createButton(title: &quot;Air Quality&quot;, action: #selector(airQualityButtonTapped), height: 45, target: self)<br>        button.isHidden = true<br>        button.contentHorizontalAlignment = .leading<br>        button.setImage(UIImage.init(systemName: &quot;wind&quot;), for: .normal)<br>        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)<br>        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)<br>        return button<br>    }()<br>    <br>    // Button to select UV index<br>    private lazy var uvIndexButton: UIButton = {<br>        let button = createButton(title: &quot;UV index&quot;, action: #selector(uvIndexButtonTapped), height: 45, target: self)<br>        button.isHidden = true<br>        button.contentHorizontalAlignment = .leading<br>        button.setImage(UIImage.init(systemName: &quot;sun.max.fill&quot;), for: .normal)<br>        button.contentEdgeInsets = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)<br>        button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -10, bottom: 0, right: 0)<br>        return button<br>    }()<br>    <br>    // Button to display additional information<br>    private lazy var infoButton: UIButton = {<br>        let button = createButton(title: &quot;What is this?&quot;, action: #selector(mainButtonTapped), height: 58, target: self)<br>        button.isHidden = true<br>        <br>        if let currentTitle = button.title(for: .normal) {<br>            let attributes: [NSAttributedString.Key: Any] = [<br>                .underlineStyle: NSUnderlineStyle.single.rawValue<br>            ]<br>            <br>            let attributedTitle = NSAttributedString(string: currentTitle, attributes: attributes)<br>            button.setAttributedTitle(attributedTitle, for: .normal)<br>        }<br>        <br>        return button<br>    }()<br>    <br>    // Circular button to visualize the current parameter<br>    private lazy var roundButton: UIButton = {<br>        let button = UIButton()<br>        let roundButtonDiameter: CGFloat = 75<br>        button.backgroundColor = .cyan<br>        button.layer.cornerRadius = roundButtonDiameter / 2<br>        button.widthAnchor.constraint(equalToConstant: roundButtonDiameter).isActive = true<br>        button.heightAnchor.constraint(equalToConstant: roundButtonDiameter).isActive = true<br>        button.setImage(UIImage.init(systemName: &quot;wind&quot;), for: .normal)<br>        return button<br>    }()<br>    <br>    // Initializer<br>    init() {<br>        super.init(frame: .zero)<br>        <br>        setupViews()<br>        setupConstraints()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    // Method to set up views<br>    func setupViews() {<br>        self.addSubview(primaryStackView)<br>        primaryStackView.addArrangedSubview(mainButton)<br>        primaryStackView.addArrangedSubview(secondaryStackView)<br>        secondaryStackView.addArrangedSubview(airQualityButton)<br>        secondaryStackView.addArrangedSubview(uvIndexButton)<br>        primaryStackView.addArrangedSubview(infoButton)<br>        self.addSubview(roundButton)<br>        <br>    }<br>    <br>    // Method to set up constraints<br>    func setupConstraints() {<br>        primaryStackView.snp.makeConstraints { make in<br>            make.top.bottom.right.left.equalToSuperview().inset(30)<br>        }<br>        <br>        roundButton.snp.makeConstraints { make in<br>            make.centerY.equalTo(mainButton)<br>            make.right.equalTo(primaryStackView).offset(20)<br>        }<br>    }<br>    <br>    // Method to create buttons to avoid duplicating code<br>    private func createButton(title: String, action: Selector, height: CGFloat, target: Any) -&gt; UIButton {<br>        let button = UIButton()<br>        button.setTitle(title, for: .normal)<br>        button.setTitleColor(.black, for: .normal)<br>        button.backgroundColor = .clear<br>        button.layer.shadowColor = UIColor.black.cgColor<br>        button.layer.shadowOffset = CGSize(width: 0, height: 2)<br>        button.layer.shadowOpacity = 0.2<br>        button.layer.shadowRadius = 4<br>        button.addTarget(target, action: action, for: .touchUpInside)<br>        button.widthAnchor.constraint(equalToConstant: Layout.screenWidth * 0.6).isActive = true<br>        button.heightAnchor.constraint(equalToConstant: height).isActive = true<br>        return button<br>    }<br>    <br>    // Action when main button is tapped<br>    @objc private func mainButtonTapped() {<br>        let areButtonsHidden = airQualityButton.isHidden<br>        <br>        airQualityButton.isHidden.toggle()<br>        uvIndexButton.isHidden.toggle()<br>        infoButton.isHidden.toggle()<br>        <br>        let image = areButtonsHidden ? UIImage(systemName: &quot;chevron.up&quot;) : UIImage(systemName: &quot;chevron.down&quot;)<br>        mainButton.setImage(image, for: .normal)<br>    }<br>    <br>    // Action when air quality button is tapped<br>    @objc private func airQualityButtonTapped() {<br>        mainButton.setTitle(&quot;Air Quality&quot;.uppercased(), for: .normal)<br>        airQualityButton.isHidden = true<br>        uvIndexButton.isHidden = true<br>        infoButton.isHidden = true<br>        roundButton.setImage(UIImage.init(systemName: &quot;wind&quot;), for: .normal)<br>        mainButton.setImage(UIImage.init(systemName: &quot;chevron.down&quot;), for: .normal)<br>        currentParameter = .airQuality<br>    }<br>    <br>    // Action when UV index button is tapped<br>    @objc private func uvIndexButtonTapped() {<br>        mainButton.setTitle(&quot;UV index&quot;.uppercased(), for: .normal)<br>        airQualityButton.isHidden = true<br>        uvIndexButton.isHidden = true<br>        infoButton.isHidden = true<br>        roundButton.setImage(UIImage.init(systemName: &quot;sun.max.fill&quot;), for: .normal)<br>        mainButton.setImage(UIImage.init(systemName: &quot;chevron.down&quot;), for: .normal)<br>        currentParameter = .uvIndex<br>    }<br>}</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3709939bf696" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rocket Launch iOS App with GraphQL Using Apollo]]></title>
            <link>https://medium.com/@quazilier/rocket-launch-ios-app-with-graphql-using-apollo-7ccf286e3461?source=rss-2b897fdd696c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ccf286e3461</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[apollo]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[uikit]]></category>
            <dc:creator><![CDATA[Cyril Vasilyev]]></dc:creator>
            <pubDate>Fri, 18 Aug 2023 15:27:14 GMT</pubDate>
            <atom:updated>2023-08-18T15:27:14.952Z</atom:updated>
            <content:encoded><![CDATA[<p>Hello everyone!</p><p>Today, we’re going to develop an iOS app that leverages a GraphQL backend via the Apollo library. This app, named “Rocket Launch”, will showcase both past and upcoming SpaceX rocket launches. We’ll get insights into mission details, including their dates and venues. For this development, we’ll be using UIKit without relying on storyboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*BENGdRIuOdJIRYY7" /></figure><p>On the main interface, rockets will be listed in a table view. Upon selecting a rocket, users will see a detailed list of its past and future launches.</p><p>Each launch in this list will display its date, location, and the type of mission.</p><h3>A Quick Overview of GraphQL, Apollo, and our SpaceX API:</h3><ul><li>GraphQL: This is an API query language that lets apps request only the specific data they need, receiving it in a JSON format. It offers precise data requests, which means servers send back only what’s asked for. This efficient approach reduces data transfer, especially when compared to traditional REST APIs, and enhances app performance. For more depth, check out the GraphQL official website.</li><li>Apollo: An impressive library tailored for GraphQL in client-side apps. It delivers powerful tools for both querying and mutating server data, along with state management. Notably, Apollo integrates seamlessly with iOS — and that’s what we’ll be harnessing for our project. You can dive deeper into Apollo on its official site.</li><li>SpaceXAPI: An excellent practice API. Here, we’ll secure the URL for our queries, access the necessary GraphQL schema, and engage with the Explorer section. This section lets us craft and execute our operations in real-time and observe the responses.</li></ul><h3>Setting Up the Project:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Z-TVKvfwuu6846qQ" /></figure><p>To kick things off, we’ll initiate a new app project in Xcode. I’ve decided on the name “rocket-launch-programmatically” because my plan is to construct it programmatically without leaning on Storyboard. Even so, during setup, make sure to select the Storyboard interface and opt for Swift as the programming language.</p><h3>Apollo Installation via Package Manager:</h3><p>Now, onto Apollo’s installation. While there are various methods like CocoaPods to do this, I’m favoring the Package Manager for this endeavor. Punch in “apollo-ios” into the search, and proceed to install the framework. All we need here is the top Package Product on the list — that’s Apollo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*o-arYO0jWH-wjWCa" /></figure><h3>CLI Installation:</h3><p>The CLI, or Command Line Interface, will be our tool of choice for generating Swift code based on the GraphQL schema. To set it in motion, open the context menu for our project by right-clicking on the top left corner of Xcode. From there, select “Install CLI”. Afterward, hit “Run” and ensure permissions are granted to alter files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eKf6g79VCNC7fz6l" /></figure><h3>Configuring the GraphQL Module:</h3><p>Let’s start by opening the Terminal and navigating to our project’s directory. In my case, it’s conveniently located right on the Desktop. To navigate there, you’d enter:</p><p>cd Desktop/rocket-launches-programmatically</p><p>With that out of the way, let’s initialize our configuration file. This particular file determines the essential parameters required for subsequent code generation.</p><p>For the init command, we need to supply a value for the schema-name argument (which will serve as the namespace for our soon-to-be-generated files) and a value for the module-type argument. The latter should be set to swiftPackageManager, implying that all future files will be linked with the main project via SPM. Thus, the command would look like:</p><p>./apollo-ios-cli init --schema-name SpaceXAPI --module-type swiftPackageManager</p><p>Upon executing this command, a configuration file will be generated.</p><h3>Downloading the Schema File:</h3><p>Our next move is to download the schema file. This document delineates all potential queries, data types, and structures. To get this done, open the tab that corresponds to our SpaceXAPI.</p><p>On the page, cast your eyes to the left-hand menu and pinpoint the “Schema” section. From there, transition into the SDL subsection. Here’s a <a href="https://studio.apollographql.com/public/SpaceX-pxxbxen/variant/current/schema/sdl">direct link</a> to this segment for easier access. Our goal now is to tap into the “Raw” file, which can be located at the top right corner of the page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zQMwRSemBs7d4ujL" /></figure><p><em>Interestingly, the file gets downloaded with a </em>.graphql<em> extension. This extension is apt solely for queries, mutations, and fragments. However, if we intend to use this file as a schema, a slight tweak is required: the extension needs to be modified to </em>.graphqls<em>. The &#39;s&#39; at the end stands for &#39;schema&#39;. For ease of reference, let&#39;s rename the file itself to &quot;schema&quot;. Thus, the end product will be aptly titled </em>schema.graphqls<em>.</em></p><p>For convenience and to maintain a structured project, let’s carve out a folder named GraphQL within our project. We&#39;ll then move our freshly renamed schema into this directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*qaQz6n-E1pbkMLEW" /></figure><p>Now, it’s time to incorporate this folder into our project. Achieve this by right-clicking in the Navigator area and adding the GraphQL folder to the project.</p><p>Once integrated, the schema and any subsequent GraphQL files will be readily accessible and neatly organized within our Xcode environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*01wZuTJtSgslBSGx" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yjYe1LmTO2bK8vES" /></figure><h3>Adding the First GraphQL Operation:</h3><p>The premier screen of our application is dedicated to displaying a list of SpaceX’s rockets. To achieve this, we’re going to revisit the SpaceX API website and make our way to the ‘Explorer’ section. Here, we’ll craft a query designed to fetch the rocket list.</p><p>In the left navigation pane, our target is the ‘rockets’ entry (take care not to confuse this with ‘Rocket’; we’re after the array). Selecting this will generate a new query in our editor.</p><p>Now, back in the navigator, let’s pinpoint and add the fields we intend to retrieve from our query. Specifically, we’ll choose the fields: ‘id’, ‘name’, ‘height’ (making sure to select just the metric in meters), and ‘mass’ (opting only for the weight in kilograms).</p><p>Taking a moment to tweak within the code editor, rename the operation from ‘Rockets’ to ‘RocketsQuery’.</p><p>When we hit the test run button, a glance at the right-hand inspector will reveal data pertaining to various rockets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XMPO10ANiG9jCvbH" /></figure><h3>Creating a File for the Operation in Xcode:</h3><p>Now, within the GraphQL folder in Xcode, let&#39;s forge ahead and generate a file named rocketsQuery bearing the .graphql extension. When you&#39;re prompted to select a file type during creation, opt for the &#39;Empty&#39; template. Once created, you can directly paste into it the query we&#39;ve just crafted.</p><p>By doing this, our Xcode environment neatly encapsulates all GraphQL related operations, providing a streamlined workflow and easy access to all our queries.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jtd_vYgE7qdh8mN0" /></figure><h3>Generating Swift Code for the Operation:</h3><p>This is where the previously mentioned CLI (Command Line Interface) comes into play. We’ll need to circle back to the Terminal and execute the generate command. This step becomes a mandate every time we modify existing operations or introduce new ones. Here&#39;s the specific Terminal command for it:</p><p>./apollo-ios-cli generate</p><p>Upon execution, within the SpaceXAPI folder, a new file named RocketsQuery.graphql will emerge, but with a .swift extension. This file essentially translates our GraphQL query into Swift code, making it integrable and executable within our iOS application.</p><p>This auto-generation ensures that we have a consistent, type-safe access layer to our GraphQL server, right within our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_i6myJlhDyE3x0Jt" /></figure><h3>Incorporating the Local SpaceXAPI Package:</h3><p>We’ve generated the graphql module, and now it’s time to incorporate the local SpaceXAPI package into our project. To do this, open the Package Manager and select the ‘Add Local…’ button located at the bottom of the interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0nmvqMHMYJr3KvIP" /></figure><p>There, you should select the SpaceXAPI folder and click on the ‘Add Package’ button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Vobh_86A92csjO4n" /></figure><p>Also, make sure to include SpaceXAPI under the ‘Frameworks’ section of our primary target.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_tmaWDzi41Q99OSN" /></figure><p>After these steps, you can easily import the package into any file using import SpaceXAPI</p><h3>Setting Up a Client for Network Operations:</h3><p>Let’s set up a straightforward client named NetworkService. This will be a swift file with a singleton pattern. It will have just one property, Apollo, to which we’ll refer whenever we wish to perform a GraphQL operation.</p><p>The Apollo property needs to be initialized with an endpoint where requests will be sent. We’ll fetch the URL from the SpaceXAPI documentation.</p><p>Below is the code for our NetworkService:</p><pre>import Apollo<br>import Foundation<br><br>final class NetworkService {<br>  static let shared = NetworkService()<br>  private(set) var apollo = ApolloClient(url: URL(string: &quot;&lt;https://spacex-production.up.railway.app/&gt;)&quot;)!)<br>  private init() { }<br>}</pre><h3>Let’s delve into the layout for RocketsViewController:</h3><p>To instantly disable the Storyboard, we’ll append the scene function in the SceneDelegate and designate our RocketsViewController, which we’ll soon establish, as the root controller. Naturally, this can be accomplished via the AppDelegate, and optionally, you can erase the Main file and everything related to the Storyboard.</p><pre>import UIKit<br><br>class SceneDelegate: UIResponder, UIWindowSceneDelegate {<br>var window: UIWindow?<br>func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {<br>        guard let windowScene = (scene as? UIWindowScene) else { return }<br>        let window = UIWindow(windowScene: windowScene)<br>        let rocketsVC = RocketsViewController()<br>        let navController = UINavigationController(rootViewController: rocketsVC)<br>        window.rootViewController = navController<br>        self.window = window<br>        window.makeKeyAndVisible()<br>    }<br>// Rest of SceneDelegate functions<br>}</pre><p>I won’t dwell on the intricacies of UITableView, assuming you’re already familiar with it. Hence, I won’t go in-depth about crafting tables and cells but will showcase the code with annotations.</p><p>For the RocketsViewController, I’ve established a distinct eponymous file. The TableView will incorporate a RocketCell, for which I’ve made a separate file. For code readability, I employ closure-based initialization.</p><p>Additionally, I use the functions setupViews() for the view hierarchy and setupConstraints() to fine-tune the layout using the SnapKit library — which I fetched via SPM.</p><h3>Crafting the RocketsViewController:</h3><p>Let’s dive right into the essence of our session. Initiate a new Swift file titled RocketsViewController. It’s crucial to remember to import the local package SpaceXAPI that we previously set up. Furthermore, I incorporate the SnapKit library for managing constraints.</p><pre>import UIKit<br>import SpaceXAPI<br>import SnapKit</pre><p>Next, we’ll establish the class for our table within the RocketsViewController view controller:</p><pre>// Final class RocketsViewController<br>final class RocketsViewController: UIViewController {<br>    // Private array rockets, containing data about rockets, we will store rockets fetched through Apollo here<br>    private var rockets: [RocketsQuery.Data.Rocket] = []<br>    // Private variable to create a table, we&#39;ll name the cell RocketCell - we will write it in a separate file<br>    private lazy var tableView: UITableView = {<br>        let tv = UITableView(frame: .zero, style: .plain)<br>        tv.dataSource = self<br>        tv.delegate = self<br>        tv.register(RocketCell.self, forCellReuseIdentifier: &quot;RocketCell&quot;)<br>        return tv<br>    }()<br>    // In viewDidLoad, we&#39;ll call functions for view hierarchy creation, constraints setup, and fetching data about rockets<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        // Table setup<br>        setupViews()<br>        setupConstraints()<br>        // Fetching rocket data, we will define this below<br>        fetchRockets()<br>    }<br>    // Function to setup view hierarchy<br>    private func setupViews() {<br>        view.addSubview(tableView)<br>    }<br>    // Function to setup constraints using SnapKit<br>    private func setupConstraints() {<br>        tableView.snp.makeConstraints { make in<br>            make.edges.equalToSuperview()<br>        }<br>    }<br>}</pre><p>Next, we’ll extend the class and set up the delegate and dataSource for our table.</p><pre>extension RocketsViewController: UITableViewDelegate, UITableViewDataSource {<br>    // Function returning the number of sections in the table (which would be the default, so this function can be omitted)<br>    func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        return 1<br>    }<br>    // Function returning the number of cells in the table section<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        // The value corresponds to the number of elements in the rockets array<br>        return rockets.count<br>    }<br>    // Function returning the title for the section<br>    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? {<br>        return &quot;Rockets&quot;<br>    }<br>    // Function for table cell configuration<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;RocketCell&quot;, for: indexPath) as! RocketCell<br>        let rocket = rockets[indexPath.row]<br>        cell.configureWith(rocket)<br>        return cell<br>    }<br>    // didSelectRowAt function, called when tapping on a table cell. We&#39;ll need this later when navigating to another view controller displaying launch info. It&#39;ll be named LaunchesViewController. For now, it can be commented out. In real life, we&#39;d write it when creating the new view controller, but to avoid confusion, let&#39;s create it now.<br>    //func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {<br>    //    let vc = LaunchesViewController()<br>    //    vc.rocket = rockets[indexPath.row]<br>    //    let navController = UINavigationController(rootViewController: vc)<br>    //    navController.modalPresentationStyle = .pageSheet<br>    //    self.present(navController, animated: true, completion: nil)<br>    //}<br>}</pre><p>We’ll then append another extension to the class for a function that will fetch data about the rockets:</p><pre>private extension RocketsViewController {<br>    // Private function to fetch rocket data<br>    func fetchRockets() {<br>  // Create a request from our graphql file<br>        let query = RocketsQuery()<br>  // Connect to our Network Service. Apollo returns the standard Swift result, we handle it using switch case<br>        NetworkService.shared.apollo.fetch(query: query) { [weak self] result in<br>            switch result {<br>            case .success(let value):<br>                // Retrieve rocket data and update the table<br>                self?.rockets = value.data?.rockets?.compactMap { $0 } ?? []<br>                DispatchQueue.main.async {<br>                    self?.tableView.reloadData()<br>                }<br>            case .failure(let error):<br>                // Print the error to the console<br>                debugPrint(error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><h3>Creating the Table Cell:</h3><p>In a separate file, we’ll create the RocketCell table cell.</p><pre>import UIKit<br>import SpaceXAPI<br>import SnapKit<br><br>// RocketCell class, inherited from UITableViewCell<br>class RocketCell: UITableViewCell {<br><br>// Create labels for the main and secondary text<br>private let nameLabel: UILabel = {<br>    let label = UILabel()<br>    label.font = .systemFont(ofSize: 16, weight: .bold)<br>    label.numberOfLines = 0<br>    return label<br>}()<br><br>private let detailLabel: UILabel = {<br>    let label = UILabel()<br>    label.font = .systemFont(ofSize: 14, weight: .regular)<br>    label.numberOfLines = 0<br>    return label<br>}()<br><br>// Cell initialization and view setup<br>override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {<br>    super.init(style: style, reuseIdentifier: reuseIdentifier)<br>    setupViews()<br>    setupConstraints()<br>}<br><br>required init?(coder: NSCoder) {<br>    fatalError(&quot;init(coder:) has not been implemented&quot;)<br>}<br><br>// The configureWith function accepts a rocket instance and sets up the cell based on the received data<br>func configureWith(_ rocket: RocketsQuery.Data.Rocket) {<br>    // Set the main cell text equal to the rocket&#39;s name<br>    nameLabel.text = rocket.name<br>    // Configure the secondary cell text, which displays the rocket&#39;s height and mass in meters and kg respectively<br>    // If data is missing, the default value of 0 is used<br>    detailLabel.text = &quot;\(rocket.height?.meters ?? 0) meters / \(rocket.mass?.kg ?? 0) kg&quot;<br>}<br><br>// Function to set up the views<br>private func setupViews() {<br>    contentView.addSubview(nameLabel)<br>    contentView.addSubview(detailLabel)<br>}<br><br>// Function to set constraints using SnapKit<br>private func setupConstraints() {<br>    nameLabel.snp.makeConstraints { make in<br>        make.top.left.equalToSuperview().offset(15)<br>        make.right.lessThanOrEqualToSuperview().offset(-15)<br>    }<br>    detailLabel.snp.makeConstraints { make in<br>        make.top.equalTo(nameLabel.snp.bottom).offset(5)<br>        make.left.right.equalTo(nameLabel)<br>        make.bottom.lessThanOrEqualToSuperview().offset(-15)<br>      }<br>   }<br>}</pre><h3>Creating a New GraphQL Operation for the LaunchesViewController:</h3><p>Much of the procedure for creating a GraphQL operation and a view controller to display the launches for each rocket is identical to what we’ve already assembled, but with some nuances.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9m5OjiQJFWqscQ8R" /></figure><p>Let’s return to our SpaceXAPI website and craft a new operation capable of fetching data on both past and upcoming rocket launches. Here’s a notable convenience of GraphQL: we can execute two different operations within a single encompassing one. We’ll soon see this in practice — in our case, it’s two operations; one for gathering data on past launches and the other for the upcoming ones. Here’s how the finished code will look:</p><pre>query LaunchesQuery($upcomingFind: LaunchFind, $pastFind: LaunchFind) {<br>  launchesUpcoming(find: $upcomingFind) {<br>    id<br>    mission_name<br>    launch_date_utc <br>  }<br>  launchesPast(find: $pastFind) {<br>    id<br>    mission_name<br>    launch_date_utc<br>  }<br>}</pre><p>In the explorer on the API website, create a new tab. On the left navigator, choose launchesUpcoming. Then, from the menu that appears, select the values id, mission_name, and launch_date_utc.</p><p>Click the back arrow in the navigator and add the operation for fetching past launches. Select the field launchesPast and place the same values: id, mission_name, and launch_date_utc.</p><p>Rename the overarching operation (currently titled LaunchesUpcoming) to LauchesQuery. As we want to fetch launches specific to a rocket, we need to add two parameters for each query. That&#39;s the find parameter where the rocket&#39;s id can be passed.</p><p>Now, head back to Xcode and craft a new Empty type file in our GraphQL folder. This file should be named launchesQuery.graphql. Incorporate our GraphQL code that describes the operation into this file. Here&#39;s a glimpse of how this should appear:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KCAhmIAerYBGMyXw" /></figure><p>Remember what we need to do next? Right, we need to generate a swift file. To do this, return to the Terminal and enter the command again:</p><p>./apollo-ios-cli generate</p><p>If a new file with the .swift extension is generated in our folder, everything is in okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CfivU1I38920POud" /></figure><h3>Creating a new view controller: LaunchesViewController:</h3><p>The new view controller, LaunchesViewController, will be displayed using “present” when a cell in the table (a specific rocket) is clicked on our initial view controller. This is why, at the end of that file, we pre-wrote the function didSelectRowAt — func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) (it&#39;s currently commented out).</p><p>So, let’s create a new Swift file named LaunchesViewController and import the necessary libraries into it.</p><pre>import SpaceXAPI<br>import UIKit<br>import SnapKit</pre><p>Now, let’s write the code for the LaunchesViewController class.</p><pre>// Final class LaunchesViewController<br>final class LaunchesViewController: UIViewController {<br>    // We need to know about a specific rocket for which we want to request a list of launches. For this, we create a variable rocket, which we will assign when clicking on a cell.<br>    var rocket: RocketsQuery.Data.Rocket!<br>    <br>    // Creating formatters for the input and output date<br>    // inDateFormatter will handle parsing the date from the query response<br>    private let inDateFormatter: DateFormatter = {<br>        let dateFormatter = DateFormatter()<br>        dateFormatter.dateFormat = &quot;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSS&#39;Z&#39;&quot;<br>        return dateFormatter<br>    }()<br>    <br>    // outDateFormatter will give the date string in the desired format<br>    private let outDateFormatter: DateFormatter = {<br>        let dateFormatter = DateFormatter()<br>        dateFormatter.dateFormat = &quot;dd-MM-yyyy HH:mm:ss&quot;<br>        return dateFormatter<br>    }()<br>    <br>    // Arrays for upcoming and past launches, here we will get data about launches when we write a function for it. It&#39;s important to understand that they refer to different types. It should be noted that they can be combined into one type using Fragment - this is a useful feature of GraphQL. But I&#39;m afraid to overload the material too much, so I suggest you explore fragments on your own.<br>    private var launchesUpcoming: [LaunchesQuery.Data.LaunchesUpcoming] = []<br>    private var launchesPast: [LaunchesQuery.Data.LaunchesPast] = []<br>    <br>    // Private variable for the table with closure initialization<br>    private lazy var tableView: UITableView = {<br>        let tv = UITableView(frame: .zero, style: .plain)<br>        tv.dataSource = self<br>        tv.delegate = self<br>        tv.register(LaunchCell.self, forCellReuseIdentifier: &quot;LaunchCell&quot;)<br>        return tv<br>    }()<br>    <br>    // Function called after the controller&#39;s view has loaded<br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        navigationItem.title = rocket.name<br>        // Table setup and loading launch data<br>        setupViews()<br>        setupConstraints()<br>        // We&#39;ll immediately call our method for parsing launch data. In real work, we would have written it only after writing the method itself, but in the format of an article, this can cause extra confusion.<br>        fetchLaunches()<br>    }<br>    <br>    // Function to set up views<br>    private func setupViews() {<br>        view.addSubview(tableView)<br>    }<br>    <br>    // Function to set constraints using SnapKit<br>    private func setupConstraints() {<br>        tableView.snp.makeConstraints { make in<br>            make.edges.equalToSuperview()<br>        }<br>    }<br>}</pre><p>Add an extension to the class for table configuration. As mentioned earlier, I won’t focus on the intricacies of creating a UITableView.</p><pre>extension LaunchesViewController: UITableViewDelegate, UITableViewDataSource {<br>    // Function returning the number of sections in the table<br>    func numberOfSections(in tableView: UITableView) -&gt; Int {<br>        return 2<br>    }<br>    <br>    // Function returning the number of rows in a table section<br>    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -&gt; Int {<br>        switch section {<br>        case 0: return launchesUpcoming.count<br>        case 1: return launchesPast.count<br>        default: return 0<br>        }<br>    }<br>    <br>    // Function to configure a table cell<br>    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>        let cell = tableView.dequeueReusableCell(withIdentifier: &quot;LaunchCell&quot;, for: indexPath) as! LaunchCell<br>        let cellText: String<br>        let cellSecondaryText: String<br>        // Setting up cells depending on the section. For displaying launch dates, we use our DateFormatter&#39;s data<br>        switch indexPath.section {<br>        case 0:<br>            let launchUpcoming = launchesUpcoming[indexPath.row]<br>            cellText = launchUpcoming.mission_name ?? &quot;&quot;<br>            let launchDate = inDateFormatter.date(from: launchUpcoming.launch_date_utc ?? &quot;&quot;) ?? .now<br>            cellSecondaryText = outDateFormatter.string(from: launchDate)<br>        case 1:<br>            let launchPast = launchesPast[indexPath.row]<br>            cellText = launchPast.mission_name ?? &quot;&quot;<br>            let launchDate = inDateFormatter.date(from: launchPast.launch_date_utc ?? &quot;&quot;) ?? .now<br>            cellSecondaryText = outDateFormatter.string(from: launchDate)<br>        default:<br>            cellText = &quot;&quot;<br>            cellSecondaryText = &quot;&quot;<br>        }<br>        // Configuring the cell<br>        cell.configureWith(text: cellText, secondaryText: cellSecondaryText)<br>        return cell<br>    }<br>    <br>    // Function returning the title for a section<br>    func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -&gt; String? {<br>        switch section {<br>        case 0: return &quot;Upcoming launches&quot;<br>        case 1: return &quot;Past launches&quot;<br>        default: return nil<br>        }<br>    }<br>}</pre><p>Create another class extension for the method to fetch launches via Apollo.</p><pre>private extension LaunchesViewController {<br>    func fetchLaunches() {<br>        // Since we need to pass the rocket id to the request, initialize LaunchFind first with rocket.id as a parameter<br>        let launchFind = LaunchFind(rocket_id: rocket.id ?? .none)<br>        <br>        // Then, initialize the query itself and pass the launchFind for both parameters<br>        let query = LaunchesQuery(upcomingFind: .some(launchFind), pastFind: .some(launchFind))<br>        <br>        // Now, through our NetworkService, perform the operation, handling the result in the completion block<br>        NetworkService.shared.apollo.fetch(query: query) { [weak self] result in<br>            switch result {<br>            case .success(let value):<br>                // In case of success, store the data in the two arrays launchesUpcoming and launchesPast, which we previously created in our class<br>                self?.launchesUpcoming = value.data?.launchesUpcoming?.compactMap { $0 } ?? []<br>                self?.launchesPast = value.data?.launchesPast?.compactMap { $0 } ?? []<br>                <br>                // Refresh the table data<br>                DispatchQueue.main.async {<br>                    self?.tableView.reloadData()<br>                }<br>                <br>            case .failure(let error):<br>                // Print error to the console<br>                debugPrint(error.localizedDescription)<br>            }<br>        }<br>    }<br>}</pre><p>Finally, create a new Swift file for the launch cell named LaunchCell.</p><pre>import UIKit<br>import SnapKit<br><br>// Final class LaunchCell, inherited from UITableViewCell<br>final class LaunchCell: UITableViewCell {<br>    <br>    // Create labels for primary and secondary text<br>    private let mainTextLabel: UILabel = {<br>        let label = UILabel()<br>        label.font = .systemFont(ofSize: 16, weight: .bold)<br>        label.numberOfLines = 0<br>        return label<br>    }()<br>    <br>    private let secondaryTextLabel: UILabel = {<br>        let label = UILabel()<br>        label.font = .systemFont(ofSize: 14, weight: .regular)<br>        label.numberOfLines = 0<br>        return label<br>    }()<br>    <br>    // Cell initialization and view setup<br>    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {<br>        super.init(style: style, reuseIdentifier: reuseIdentifier)<br>        setupViews()<br>        setupConstraints()<br>    }<br>    <br>    required init?(coder: NSCoder) {<br>        fatalError(&quot;init(coder:) has not been implemented&quot;)<br>    }<br>    <br>    // The configureWith function accepts primary and secondary text, and configures the cell according to the received data<br>    func configureWith(text: String, secondaryText: String) {<br>        // Set the primary text of the cell to the passed text<br>        mainTextLabel.text = text<br>        // Set the secondary text of the cell to the passed secondary text<br>        secondaryTextLabel.text = secondaryText<br>    }<br>    <br>    // Function to set up the views<br>    private func setupViews() {<br>        contentView.addSubview(mainTextLabel)<br>        contentView.addSubview(secondaryTextLabel)<br>    }<br>    <br>    // Function to set up constraints using SnapKit<br>    private func setupConstraints() {<br>        mainTextLabel.snp.makeConstraints { make in<br>            make.top.left.equalToSuperview().offset(15)<br>            make.right.lessThanOrEqualToSuperview().offset(-15)<br>        }<br>        <br>        secondaryTextLabel.snp.makeConstraints { make in<br>            make.top.equalTo(mainTextLabel.snp.bottom).offset(5)<br>            make.left.right.equalTo(mainTextLabel)<br>            make.bottom.lessThanOrEqualToSuperview().offset(-15)<br>        }<br>    }<br>}</pre><p>In this tutorial, we journeyed through the intricacies of iOS development, leveraging both GraphQL and the UIKit framework. We started by setting up our view controller, LaunchesViewController, where we fetched and displayed upcoming and past launches of specific rockets. Utilizing the power of GraphQL, we created efficient queries that fetched precisely the data we needed, reducing overhead and improving performance.</p><p>Additionally, we introduced the concept of formatting and presenting dates, ensuring that users receive information in a friendly and comprehensible format. Our exploration into table views showcased how to dynamically separate upcoming and past launches into distinct sections, making navigation intuitive for users.</p><p>Lastly, we dove deep into creating a custom table view cell, LaunchCell, that effectively displays the launch data in a clean and organized manner. By utilizing the SnapKit library, we made our layout code concise and easily readable, further highlighting the importance of third-party libraries in rapid iOS development.</p><p>Whether you’re a seasoned iOS developer or just getting started, we hope this tutorial offered insights and techniques to enhance your app-building journey. Remember, while tools and libraries evolve, the core principles of clean code and user-centric design remain timeless. Keep exploring, keep learning, and most importantly, keep launching your ideas into the digital universe!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ccf286e3461" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>