<?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 Burak EKMEN on Medium]]></title>
        <description><![CDATA[Stories by Burak EKMEN on Medium]]></description>
        <link>https://medium.com/@burakekmen?source=rss-47c57757afd8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JBQhZpOz5aQLjbkLoPZNHA.jpeg</url>
            <title>Stories by Burak EKMEN on Medium</title>
            <link>https://medium.com/@burakekmen?source=rss-47c57757afd8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:54:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@burakekmen/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[Building Spotlight Onboarding Flows in Swift with BEOnboardingPopup]]></title>
            <link>https://medium.com/@burakekmen/building-spotlight-onboarding-flows-in-swift-with-beonboardingpopup-2fb7524a89cc?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2fb7524a89cc</guid>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[onboarding]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Wed, 03 Dec 2025 12:48:27 GMT</pubDate>
            <atom:updated>2025-12-13T04:46:15.484Z</atom:updated>
            <content:encoded><![CDATA[<p>A high-performance <strong>Open Source</strong> library for building <strong>User Onboarding</strong> flows in <strong>Swift</strong>. Create <strong>Spotlight</strong> style <strong>Feature Walkthroughs</strong> using <strong>Pure UIKit</strong> without Storyboards.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Vuuylqs1RvaGV0scozhKA.png" /></figure><p>User onboarding is arguably the most critical part of any mobile application. You have seconds to show users the value of your app before they lose interest. A “feature tour” or “walkthrough” is a great way to highlight key functionalities, but building one from scratch — handling coordinate conversions, overlays, and animations — is often a headache.</p><p>Enter <a href="https://github.com/burakekmen/BEOnboardingPopup"><strong>BEOnboardingPopup</strong></a>.</p><p>I recently built and open-sourced this library to solve a specific problem: <strong>I needed a lightweight, highly customizable, and easy-to-implement onboarding solution that highlights specific UI elements.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/150/1*KJTCvQdFrOlwTGp2CjJpIg@2x.jpeg" /></figure><p>In this article, I’ll show you how to integrate BEOnboardingPopup into your iOS app, customize it to fit your brand, and even use it within SwiftUI.</p><h3>Why BEOnboardingPopup?</h3><p>There are plenty of onboarding libraries out there, but many are bloated, rely on old patterns, or are difficult to customize. <strong>BEOnboardingPopup</strong> focuses on:</p><ul><li><strong>Spotlight Effect:</strong> It dims the background and “cuts out” a hole for the target view, drawing the user’s attention immediately.</li><li><strong>Pure UIKit:</strong> No Storyboards, no XIBs. Just clean, readable Swift code.</li><li><strong>Auto Layout Magic:</strong> You don’t need to manually calculate frames. Just pass the UIView reference, and the library handles the rest (even converting coordinates from nested subviews).</li><li><strong>Manager Pattern:</strong> A simple Singleton manager handles the state and flow.</li><li><strong>Theme Support:</strong> Supports Dark Mode, dynamic fonts, and complete color customization out of the box.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*nUjIkMSu1bB341CBHkK-Cg.gif" /></figure><h3>📲 Installation</h3><p>The library supports <strong>Swift Package Manager (SPM)</strong>, making installation a breeze.</p><ol><li>In Xcode, go to <strong>File &gt; Add Packages…</strong></li><li>Paste the repository URL: <a href="https://github.com/burakekmen/BEOnboardingPopup.git">https://github.com/burakekmen/BEOnboardingPopup.git</a></li><li>Click <strong>Add Package</strong>.</li></ol><p>That’s it! You are ready to go.</p><h3>🚀 Quick Start: Creating Your First Tour</h3><p>Let’s say you have a ViewController with a <strong>Profile Button</strong> and a <strong>Settings Button</strong>, and you want to guide the user through them.</p><h3>Step 1: Define Your Steps</h3><p>First, create an enum that conforms to BEOnboardingStepable. This keeps your content organized and type-safe.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/941fc2d870fe242ee5fd61a964d6a012/href">https://medium.com/media/941fc2d870fe242ee5fd61a964d6a012/href</a></iframe><h3>Step 2: Launch the Popup</h3><p>In your View Controller, map your steps to the actual UIViews. The BEOnboardingPopupManager takes care of the presentation logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2f362ff8e4d55ece70400ca210504935/href">https://medium.com/media/2f362ff8e4d55ece70400ca210504935/href</a></iframe><p><strong>Result:</strong> The library will automatically find the screen coordinates of profileButton, dim the background, create a spotlight effect, and show the popup box next to it. When the user clicks &quot;Next&quot;, it animates to the settingsButton.</p><h3>🎨 Advanced Customization (Theming)</h3><p>One size rarely fits all. Your app has a specific color palette and font style. BEOnboardingPopup comes with a powerful Theme engine.</p><p>You can customize almost everything:</p><ul><li><strong>Colors:</strong> Background, Text, Buttons, Overlay opacity.</li><li><strong>Fonts:</strong> Title, Description, Buttons.</li><li><strong>Dimensions:</strong> Popup width, Corner radius, Image height.</li><li><strong>Text:</strong> Button labels (“Next”, “Back”, “Got it”).</li></ul><h3>Creating a Custom Theme</h3><p>Let’s create a modern “Ocean Blue” theme:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ad913e3778fa9327dcbcfecb67ad016/href">https://medium.com/media/9ad913e3778fa9327dcbcfecb67ad016/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*DVu6i6rfQElN013lxYGtvA.gif" /><figcaption><em>See how the library adapts to different themes dynamically.</em></figcaption></figure><h3>🛠 Using with SwiftUI</h3><p>“But wait,” I hear you ask, “I’m using SwiftUI. Can I use this?”</p><p><strong>Yes!</strong> Since the library is based on finding screen coordinates (frames), you can bridge it easily using GeometryReader.</p><p>Here is a quick <strong>workaround</strong> to capture frames in SwiftUI and pass them to the library:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b092f083945169809a7e4b8609b114f/href">https://medium.com/media/2b092f083945169809a7e4b8609b114f/href</a></iframe><h3>Conclusion</h3><p>Building a great onboarding experience shouldn’t be hard. BEOnboardingPopup handles the heavy lifting of geometry and animations, letting you focus on the content and the user journey.</p><p>The library is <strong>open-source</strong> and available on GitHub. I’d love for you to try it out, open issues if you find bugs, and — if you find it useful — <strong>give it a star! ⭐️</strong></p><p>🔗 <strong>GitHub Repository:</strong> <a href="https://www.google.com/search?q=https://github.com/burakekmen/BEOnboardingPopup">https://github.com/burakekmen/BEOnboardingPopup</a></p><p>Looking forward to seeing you in the next post. Take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2fb7524a89cc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speech-to-Text: Building a Clean, Modular Voice Manager in iOS with Swift]]></title>
            <link>https://medium.com/@burakekmen/speech-to-text-building-a-clean-modular-voice-manager-in-ios-with-swift-4eba58606c8c?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/4eba58606c8c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[avaudioengine]]></category>
            <category><![CDATA[speech-recognition]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Mon, 01 Dec 2025 13:29:44 GMT</pubDate>
            <atom:updated>2025-12-03T08:41:56.341Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pXcrNmdPuaJg3o0rUDj2UA.png" /></figure><p>How to tame SFSpeechRecognizer and AVAudioEngine into a reusable, production-ready component.</p><p>If you have ever implemented Speech-to-Text in an iOS app, you know the drill: the boilerplate code for SFSpeechRecognizer can get messy fast. You find yourself juggling permission requests, AVAudioSession configurations, and delegate callbacks all within a single View Controller. Before you know it, you have a Massive View Controller on your hands.</p><p>Today, I want to share a cleaner approach. We are going to build a reusable VoiceToTextManager that handles the heavy lifting—state management, native permission chaining, and even auto-stop functionality when the user goes silent.</p><p>Apple’s Speech framework is powerful, but it’s sensitive. You need to handle microphone access, speech recognition authorization, and the audio engine’s state simultaneously. My goal with this manager was to solve three specific problems:</p><ol><li><strong>State Management:</strong> Explicitly knowing if the app is .listening, .idle, or .stopped.</li><li><strong>Silence Detection:</strong> Automatically stopping the session if the user stops speaking for a few seconds.</li><li><strong>Clean Architecture:</strong> Keeping the UI logic completely separate from the AVAudioNode intricacies.</li><li><strong>Managing State Like a Pro</strong> Instead of using random boolean flags like isRecording, we use a clear Enum to track the lifecycle. This makes reactive UI updates much easier.</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57e15e97494499ea6b0bf32ae0ee1172/href">https://medium.com/media/57e15e97494499ea6b0bf32ae0ee1172/href</a></iframe><p><strong>2. Native Permission Chaining</strong> We don’t need external libraries to handle permissions. We can chain the native API calls to ensure we have both Speech Recognition and Microphone access before we start the audio engine.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f54fe7c3c29119991921e3a60852cb1/href">https://medium.com/media/6f54fe7c3c29119991921e3a60852cb1/href</a></iframe><p><strong>3. The “Inactivity Timer” (UX Polish)</strong> This is a feature often overlooked in tutorials. If a user finishes a sentence and stops talking, they shouldn’t have to manually press a “Stop” button every time. I implemented a timer that resets every time a new text segment is recognized. If 3 seconds pass with no new input, the app gracefully stops listening.</p><p><strong>A Note on Haptic Feedback</strong> When the recording stops (either manually or via the timer), providing physical feedback is crucial for a good user experience. In the code below, I’ve used a standard UIImpactFeedbackGenerator.</p><blockquote><strong>Pro Tip:</strong> Haptic feedback is an art form in itself. If you want to dive deeper into creating immersive tactile experiences in iOS, check out my detailed guide: <a href="https://medium.com/@burakekmen/using-haptic-feedback-in-ios-applications-2cb0a997a0e7"><strong>Using Haptic Feedback in iOS Applications</strong></a>.</blockquote><h3>Crucial Step: Info.plist Configuration</h3><p>Before running the code, you <strong>must</strong> add the following privacy keys to your project’s Info.plist file. iOS requires you to explicitly explain why your app needs access to sensitive hardware.</p><p>If you skip this step, your app will crash immediately upon requesting permissions.</p><p>Add these keys with a user-friendly description:</p><p><strong>1. NSMicrophoneUsageDescription</strong></p><ul><li><em>Value:</em> “We need access to the microphone to record your speech.”</li></ul><p><strong>2. NSSpeechRecognitionUsageDescription</strong></p><ul><li><em>Value:</em> “We need this permission to transcribe your speech into text.”</li></ul><p>Without these entries, the operating system will block the access attempts for privacy reasons.</p><p>Here is the complete, drop-in ready VoiceToTextManager class. It uses native APIs, handles memory safely with weak self, and includes the inactivity logic we discussed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b772ae0e64a61f4e02bb252fd6e15985/href">https://medium.com/media/b772ae0e64a61f4e02bb252fd6e15985/href</a></iframe><p><strong>How to Use It</strong> Integrating this into your View Controller is straightforward. You keep your UI logic clean and let the manager handle the rest.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f10c5c679160011d708a6d9002b94097/href">https://medium.com/media/f10c5c679160011d708a6d9002b94097/href</a></iframe><p><strong>Why this setup works:</strong></p><ol><li><strong>Lazy Initialization:</strong> UI components are created only when needed, keeping the memory footprint optimized.</li><li><strong>Constraint-Based Layout:</strong> The UI adapts to any screen size (iPhone SE to 15 Pro Max).</li><li><strong>Visual Feedback:</strong> The button changes color, icon, and scale (pulsing effect) based on the ListeningStatus. This is crucial for user trust.</li><li><strong>Auto-Scroll:</strong> As text gets longer, the UITextView automatically scrolls to show the latest words.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/473/1*Gq_fVEs44Cc49WtSlZMp2w.gif" /></figure><p><strong>Note:</strong> Don’t forget to update your Info.plist. You need to add NSMicrophoneUsageDescription and NSSpeechRecognitionUsageDescription with valid description strings. Otherwise, the app will crash at runtime due to missing privacy declarations.</p><p>Looking forward to seeing you in the next post. Take care!</p><ul><li><a href="https://developer.apple.com/documentation/speech/sfspeechrecognizer">SFSpeechRecognizer | Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/speech/asking_permission_to_use_speech_recognition">Asking Permission to Use Speech Recognition | Apple Developer Documentation</a></li><li><a href="https://medium.com/@burakekmen/using-haptic-feedback-in-ios-applications-2cb0a997a0e7">Using Haptic Feedback in iOS Applications</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4eba58606c8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Memory Leaks in iOS: The Fastest Way to Spot & Fix Them]]></title>
            <link>https://medium.com/@burakekmen/memory-leaks-in-ios-the-fastest-way-to-spot-fix-them-fbef90a87edb?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/fbef90a87edb</guid>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[memory-management]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Wed, 13 Aug 2025 16:19:52 GMT</pubDate>
            <atom:updated>2025-08-13T16:19:52.076Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qyY4gpQdolOOivjnmzRWLA.png" /></figure><p>Memory leaks can quietly drag down your app’s performance and eat up battery without making much noise at first. Most of the time, you don’t even notice them until something feels… off. And let’s be real, no one has time to sit with Instruments for hours.</p><p>In this post, I’ll show you how I catch and fix leaks in 5–10 minutes with a simple routine I use in every project. No over-explaining, just the stuff that actually helps. Let’s jump right in 🚀</p><h3>🚀 Quick Recap</h3><ul><li>Run your app, go through a few screens, then open the <strong>Memory Graph</strong> (💠).</li><li>If your view controller (VC) doesn’t disappear from memory after it’s dismissed — something is holding onto it.</li><li>If you want to dig deeper, use <strong>Instruments → Leaks + Allocations</strong> and take a short recording.</li><li>Usual suspects: closures, delegates, Timer, NotificationCenter, async/Combine streams.</li></ul><h3>Why does this matter?</h3><p>Imagine this: you close a screen, but network calls are still going, animations are still running, and CPU usage goes up. It’s usually a sign that something’s sticking around in memory when it shouldn’t. CI can’t always catch these — but you can, quickly, during local dev.</p><h3>1) Fastest way: Xcode Memory Graph</h3><ol><li>Run your app in Debug mode.</li><li>Go through a typical flow, then close a screen.</li><li>Tap the 💠 icon at the bottom of the debug bar.</li><li>Look under <strong>Cycles</strong>: are there reference loops?</li><li>If a view controller you dismissed is still in memory — that’s your leak.</li></ol><p>💡 Pro tip: Drop a quick print(“deinit: HomeVC”) log in your deinit. Don’t forget to remove it before release 😉</p><h3>2) Go a bit deeper: Instruments</h3><ol><li>From Xcode, go to <strong>Product → Profile (⌘I)</strong>.</li><li>Pick <strong>Leaks</strong> from the Instruments template.</li><li>Hit Record and use the app like a user.</li><li>Switch between Leaks and Allocations views.</li><li>Watch memory usage. If it spikes and stays high, you probably have a leak.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*eXv5oE5eTYWc__uD8X8X8Q.png" /></figure><h3>3) Most common leak cases I see</h3><h4>A) Closures capturing self strongly (this is usually the culprit in closures — just use [weak self] to be safe)</h4><pre>fetchUser { [weak self] user in<br>    self?.updateUI()<br>}</pre><p>Always use [weak self] inside closures that outlive the current scope.</p><h4>B) Delegates not marked weak</h4><pre>weak var delegate: MyDelegate?</pre><p>If it’s a delegate, it should be weak. Period.</p><h4>C) Timer not invalidated</h4><pre>final class MyTicker {<br>    var timer: Timer?<br>    <br>    func start() {<br>        timer = Timer.scheduledTimer(...)<br>    }<br><br>    deinit {<br>        timer?.invalidate()<br>    }<br>}</pre><p>Timers don’t know when to stop on their own — if you don’t invalidate them, they’ll keep going even after the screen is gone.</p><h4>D) Forgot to remove NotificationCenter observers</h4><pre>deinit {<br>    NotificationCenter.default.removeObserver(self)<br>}</pre><p>If you add observers, always clean them up in deinit.</p><h4>E) Async tasks or Combine subscriptions not cancelled</h4><pre>deinit {<br>    task?.cancel()<br>}</pre><p>If you start long-living work (like Task or Publisher), cancel it in deinit.</p><h3>4) Quick daily routine (takes 5–10 mins max)</h3><ol><li>Walk through key screens (open → close).</li><li>Check Memory Graph — are VCs still around?</li><li>Record a short session in Instruments. Does memory return to baseline?</li></ol><h3>5) Things that look like leaks but aren’t</h3><ul><li><strong>Singletons</strong> or caches that are meant to stay in memory.</li><li><strong>3rd-party SDKs</strong> (ads, analytics) can keep things alive in the background.</li><li>Prefer weak over unowned unless you 100% guarantee object lifecycle.</li></ul><h3>Final thoughts</h3><p>Tracking down memory leaks doesn’t have to be a nightmare. Build the reflex, trust your tools, and check regularly. It’ll pay off big time in performance, battery, and even crash rates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fbef90a87edb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Story Sharing on Facebook & Instagram in iOS Apps]]></title>
            <link>https://medium.com/@burakekmen/story-sharing-on-facebook-instagram-in-ios-apps-2df2a82ebf96?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2df2a82ebf96</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[facebook]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 10:13:14 GMT</pubDate>
            <atom:updated>2024-12-26T14:19:55.635Z</atom:updated>
            <content:encoded><![CDATA[<p>Story sharing is an effective way to increase user engagement by adding social media integration to your app. In this article, I’ll show you how to implement photo story sharing on Facebook and Instagram in iOS apps. We will cover step-by-step code examples, necessary Info.plist configurations, and the details you need for integration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3S_2eYnpTwkTWNBrjxXsrQ.png" /></figure><h3><strong>How Does Story Sharing Work?</strong></h3><p>Facebook and Instagram use the Pasteboard API for story sharing. Pasteboard is a mechanism that allows data transfer from your app to another app. For example, when you want to share a story:</p><ul><li>Images and other media content are written to the Pasteboard.</li><li>These contents are transferred using special keys defined by Facebook or Instagram (e.g., com.instagram.sharedSticker.backgroundImage).</li><li>The app is opened via URL Scheme, reads the content from the Pasteboard, and shows the user the sharing screen.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*B65A5808LoGYXDNdVZatOg.gif" /></figure><h3><strong>Before You Start:</strong></h3><p>For <strong>Facebook</strong> story sharing, your app <strong>needs to have a Facebook App ID</strong>. You can obtain an <strong>App ID</strong> by creating an app on the <a href="https://developers.facebook.com/"><strong>Facebook Developer Panel</strong></a><strong>.</strong></p><h4><strong>Info.plist Configurations</strong></h4><p>You need to add some URL Scheme configurations to your <strong>Info.plist</strong> file for Facebook and Instagram integration:</p><pre>&lt;key&gt;LSApplicationQueriesSchemes&lt;/key&gt;<br>&lt;array&gt;<br>    &lt;string&gt;instagram-stories&lt;/string&gt;<br>    &lt;string&gt;facebook-stories&lt;/string&gt;<br>&lt;/array&gt;</pre><h3><strong>Manager Class</strong></h3><p>Creating a class to manage story sharing will help keep your code organized and easy to maintain. This class will interact with both social media platforms and handle the process of sending content to the user.</p><pre>enum SMSMOptionKey: String {<br>    case appIdFacebook = &quot;com.facebook.sharedSticker.appID&quot;<br>    case backgroundImageFacebook = &quot;com.facebook.sharedSticker.backgroundImage&quot;<br>    case backgroundImageInstagram = &quot;com.instagram.sharedSticker.backgroundImage&quot;<br>}<br><br>enum SMSMPlatformUrlScheme: String {<br>    case facebook = &quot;facebook-stories://share&quot;<br>    case instagram = &quot;instagram-stories://share&quot;<br>}<br><br>enum SMSMPlatformAppStoreUrl: String {<br>    case facebook = &quot;https://apps.apple.com/app/facebook/id284882215&quot;<br>    case instagram = &quot;https://apps.apple.com/app/instagram/id389801252&quot;<br>}<br><br>enum SMSMShareButtonType {<br>    case facebook<br>    case instagram<br>}<br><br>struct SMSMWarningInfoModel {<br>    let title: String<br>    let message: String<br>    let appStoreRedirectUrl: String?<br>}<br><br>final class SocialMediaShareManager {<br>    static let shared = SocialMediaShareManager()<br>    private init() {}<br>    <br>    func shareToPlatform(type: SMSMShareButtonType,<br>                         storyImage: UIImage?,<br>                         warningCompletion: ((SMSMWarningInfoModel) -&gt; Void)?) {<br>        <br>        var urlScheme: URL?<br>        var pasteboardItems: [String: Any] = [:]<br>        <br>        switch type {<br>        case .facebook:<br>            urlScheme = URL(string: SMSMPlatformUrlScheme.facebook.rawValue)<br>            pasteboardItems = preparePasteboardItems(<br>                appID: &quot;FACEBOOK_APP_ID&quot;,<br>                appIDKey: .appIdFacebook,<br>                image: storyImage,<br>                imageKey: .backgroundImageFacebook<br>            )<br>            <br>        case .instagram:<br>            urlScheme = URL(string: &quot;\(SMSMPlatformUrlScheme.instagram.rawValue)?source_application=\(Bundle.main.appName)&quot;)<br>            pasteboardItems = preparePasteboardItems(<br>                image: storyImage,<br>                imageKey: .backgroundImageInstagram<br>            )<br>            <br>        }<br>        <br>        guard let urlScheme, validateURLScheme(type, urlScheme, warningCompletion: warningCompletion) else { return }<br>        guard storyImage != nil else {<br>            warningCompletion?(prepareWarningModel(message: &quot;Try Again Later&quot;))<br>            return<br>        }<br>        <br>        shareWithPasteboard(urlScheme: urlScheme, items: pasteboardItems)<br>    }<br>}<br><br>private extension SocialMediaShareManager {<br>    <br>    func validateURLScheme(_ type: SMSMShareButtonType, _ urlScheme: URL, warningCompletion: ((SMSMWarningInfoModel) -&gt; Void)?) -&gt; Bool {<br>        guard UIApplication.shared.canOpenURL(urlScheme) else {<br>            warningCompletion?(prepareWarningModel(<br>                title: &quot;App Not Installed on The Phone&quot;,<br>                message: &quot;Please Install The App Then Try Later&quot;,<br>                appStoreRedirectUrl: getAppStoreUrl(type: type)<br>            ))<br>            return false<br>        }<br>        return true<br>    }<br>    <br>    <br>    func preparePasteboardItems(appID: String? = nil,<br>                                appIDKey: SMSMOptionKey? = nil,<br>                                image: UIImage?,<br>                                imageKey: SMSMOptionKey) -&gt; [String: Any] {<br>        var items: [String: Any] = [:]<br>        <br>        if let appID,<br>           let appIDKey {<br>            items[appIDKey.rawValue] = appID<br>        }<br>        <br>        if let imageData = image?.pngData() {<br>            items[imageKey.rawValue] = imageData<br>        }<br>        <br>        return items<br>    }<br>    <br>    <br>    func shareWithPasteboard(urlScheme: URL, items: [String: Any]) {<br>        let pasteboardOptions: [UIPasteboard.OptionsKey: Any] = [<br>            .expirationDate: Date().addingTimeInterval(300)<br>        ]<br>        <br>        UIPasteboard.general.setItems([items], options: pasteboardOptions)<br>        UIApplication.shared.open(urlScheme, options: [:], completionHandler: nil)<br>    }<br>}<br><br><br>internal extension SocialMediaShareManager {<br>    <br>    func getAppStoreUrl(type: SMSMShareButtonType) -&gt; String {<br>        switch type {<br>        case .facebook:<br>            SMSMPlatformAppStoreUrl.facebook.rawValue<br>        case .instagram:<br>            SMSMPlatformAppStoreUrl.instagram.rawValue<br>        }<br>    }<br>    <br>    func prepareWarningModel(title: String = &quot;Warning&quot;,<br>                             message: String,<br>                             appStoreRedirectUrl: String? = nil) -&gt; SMSMWarningInfoModel {<br>        SMSMWarningInfoModel(title: title,<br>                             message: message,<br>                             appStoreRedirectUrl: appStoreRedirectUrl)<br>    }<br>    <br>}</pre><h4><strong>Using Pasteboard</strong></h4><p>During story sharing, data is written to the Pasteboard for a certain period. The code below adds data to the Pasteboard:</p><pre>func shareWithPasteboard(urlScheme: URL, items: [String: Any]) {<br>    let pasteboardOptions: [UIPasteboard.OptionsKey: Any] = [<br>        .expirationDate: Date().addingTimeInterval(300) // 5 minute<br>    ]<br>    UIPasteboard.general.setItems([items], options: pasteboardOptions)<br>    UIApplication.shared.open(urlScheme, options: [:], completionHandler: nil)<br>}</pre><p><strong>Why Do We Use Pasteboard?</strong></p><ul><li>To quickly transfer data to other apps.</li><li>Facebook and Instagram read data from the Pasteboard.</li><li>It is a secure and standard method.</li></ul><h4><strong>Checking Apps are Installed</strong></h4><p>If the user doesn’t have the relevant app installed on their device, sharing cannot proceed. In this case, a redirect to the App Store is triggered:</p><pre>func validateURLScheme(_ type: SMSMShareButtonType, _ urlScheme: URL, warningCompletion: ((SMSMWarningInfoModel) -&gt; Void)?) -&gt; Bool {<br>    guard UIApplication.shared.canOpenURL(urlScheme) else {<br>        warningCompletion?(SMSMWarningInfoModel(<br>            title: &quot;App Not Installed&quot;,<br>            message: &quot;Please install the app and try again.&quot;,<br>            appStoreRedirectUrl: getAppStoreUrl(type: type)<br>        ))<br>        return false<br>    }<br>    return true<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*umF2VlelNX6e_oSKPMhDdA.png" /></figure><h3><strong>ViewController Class</strong></h3><p>Let’s try using a simple example. In this example, I obtained the image to be shared as a story from the view. Alternatively, you can ask the user to select a photo from their album. Since the Manager class accepts the UIImage data type, how you obtain the image to share is up to you.</p><pre>class ViewController: UIViewController {<br><br>    @IBOutlet private weak var containerView: UIView!<br>    @IBOutlet private weak var subView: UIView!<br>    @IBOutlet private weak var imgBlur: UIImageView!<br>    @IBOutlet private weak var imgLocation: UIImageView!<br>    @IBOutlet private weak var btnInstagram: UIButton!<br>    @IBOutlet private weak var btnFacebook: UIButton!<br>    <br>    private let shareManager = SocialMediaShareManager.shared<br>    <br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        <br>        prepareUI()<br>    }<br><br>    func prepareUI() {<br>        imgBlur.addBlurEffect()<br>        subView.roundCornersEachCorner(.allCorners, radius: 5)<br>    }<br>    <br>    @IBAction func instagramStoryTapped(_ sender: UIButton) {<br>        handleStoryProcess(type: .instagram)<br>    }<br>        <br>    @IBAction func facebookStoryTapped(_ sender: UIButton) {<br>        handleStoryProcess(type: .facebook)<br>    }<br>}<br><br><br>extension ViewController {<br>    <br>    func handleStoryProcess(type: SMSMShareButtonType) {<br>        let storyImage = containerView.asImage()<br>        shareManager.shareToPlatform(<br>            type: type,<br>            storyImage: storyImage,<br>            warningCompletion: { [weak self] warningInfo in<br>                guard let self else { return }<br>                <br>                if let appStoreRedirectUrl = warningInfo.appStoreRedirectUrl {<br>                    self.showAlert(<br>                        title: warningInfo.title,<br>                        message: warningInfo.message,<br>                        positiveButtonText: &quot;Install Now&quot;,<br>                        positiveButtonClickListener: { [weak self] in<br>                            self?.openUrl(url: appStoreRedirectUrl)<br>                        },<br>                        negativeButtonText: &quot;Ok&quot;<br>                    )<br>                } else {<br>                    self.showAlert(<br>                        title: warningInfo.title,<br>                        message: warningInfo.message)<br>                }<br>                <br>            })<br>    }<br>    <br>}</pre><p>In this example, we’re creating the image from the view components and using it. I chose this approach to explain the example, but you can allow the user to select a photo from their album and share that as a story.</p><p>With this example, I tried to demonstrate how simple usage can be implemented. You can modify it based on your needs.</p><p>Looking forward to seeing you in the next post. Take care!</p><p>You can find the code for the example project here:</p><p><a href="https://github.com/burakekmen/StoryShare">GitHub - burakekmen/StoryShare: Facebook &amp; Instagram Story Sharing in iOS App</a></p><p>Documentations:</p><ul><li><a href="https://developers.facebook.com/docs/sharing/sharing-to-stories/">Sharing to Stories - Documentation - Meta for Developers</a></li><li><a href="https://developers.facebook.com/docs/instagram-platform/sharing-to-stories">Sharing to Stories - Instagram Platform - Documentation - Meta for Developers</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2df2a82ebf96" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Haptic Feedback in iOS Applications]]></title>
            <link>https://medium.com/@burakekmen/using-haptic-feedback-in-ios-applications-2cb0a997a0e7?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cb0a997a0e7</guid>
            <category><![CDATA[haptic-feedback]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[user-experience]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Thu, 05 Dec 2024 18:10:37 GMT</pubDate>
            <atom:updated>2024-12-05T18:10:37.931Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7J_ZY-37NOtBGJyIU2tGZA.png" /></figure><p>Haptic feedback enhances user interactions in iOS apps by providing tactile responses via the device’s vibration motor. This feature allows users to feel a physical reaction to their actions, improving the overall user experience. In this article, we’ll explore the types of haptic feedback available in iOS, manage them using a centralized class, and provide usage examples in a ViewController.</p><h3>What Is Haptic Feedback and Why Use It?</h3><p>Haptic feedback adds a layer of tactile interaction to visual and auditory responses. For example:</p><ul><li><strong>To emphasize success:</strong> A light vibration can be used.</li><li><strong>To indicate errors:</strong> A strong vibration helps draw attention.</li><li><strong>To make warnings more noticeable:</strong> A rigid vibration makes the message clear.</li></ul><p>When used correctly, haptic feedback significantly enhances the user experience by making the app more interactive and intuitive.</p><h3>Types of Haptic Feedback</h3><p>Apple provides three main classes to deliver haptic feedback:</p><h4>1. UIImpactFeedbackGenerator</h4><p>This class simulates physical impacts:</p><ul><li><strong>light:</strong> A subtle vibration, suitable for minor errors or gentle feedback.</li><li><strong>medium:</strong> Provides a noticeable vibration, often used for prominent actions.</li><li><strong>heavy:</strong> A strong vibration for critical interactions.</li><li><strong>soft:</strong> (iOS 13 and later) A delicate vibration for refined feedback.</li><li><strong>rigid:</strong> (iOS 13 and later) A sharp vibration for critical errors or noticeable feedback.</li></ul><h4>2. UINotificationFeedbackGenerator</h4><p>Used for communicating the outcome of an event:</p><ul><li><strong>success:</strong> Indicates a task was successfully completed.</li><li><strong>warning:</strong> Alerts users to a situation requiring attention.</li><li><strong>error:</strong> Signals an error or failure in an operation.</li></ul><h4>3. UISelectionFeedbackGenerator</h4><p>Provides feedback when a selection changes, such as scrolling through a date picker.</p><h3>HapticFeedbackManager: Centralized Management</h3><p>To manage haptic feedback efficiently, you can centralize its implementation in a reusable class. Below is the HapticFeedbackManager class:</p><pre>import UIKit<br><br>// Enum representing different haptic feedback types<br>enum HapticFeedbackType {<br>    case light, medium, heavy, soft, rigid, success, warning, error<br>}<br><br>class HapticFeedbackManager {<br>    static let shared = HapticFeedbackManager()<br><br>    // Feedback generators<br>    private lazy var lightImpactGenerator = UIImpactFeedbackGenerator(style: .light)<br>    private lazy var mediumImpactGenerator = UIImpactFeedbackGenerator(style: .medium)<br>    private lazy var heavyImpactGenerator = UIImpactFeedbackGenerator(style: .heavy)<br>    private lazy var notificationGenerator = UINotificationFeedbackGenerator()<br>    private lazy var softImpactGenerator: UIImpactFeedbackGenerator? = {<br>        if #available(iOS 13.0, *) {<br>            return UIImpactFeedbackGenerator(style: .soft)<br>        }<br>        return nil<br>    }()<br>    private lazy var rigidImpactGenerator: UIImpactFeedbackGenerator? = {<br>        if #available(iOS 13.0, *) {<br>            return UIImpactFeedbackGenerator(style: .rigid)<br>        }<br>        return nil<br>    }()<br><br>    private init() {<br>        prepareAllGenerators()<br>    }<br><br>    // Prepares all feedback generators to reduce delay<br>    private func prepareAllGenerators() {<br>        DispatchQueue.main.async { [weak self] in<br>            self?.lightImpactGenerator.prepare()<br>            self?.mediumImpactGenerator.prepare()<br>            self?.heavyImpactGenerator.prepare()<br>            self?.notificationGenerator.prepare()<br>            self?.softImpactGenerator?.prepare()<br>            self?.rigidImpactGenerator?.prepare()<br>        }<br>    }<br><br>    // Triggers the appropriate haptic feedback<br>    func trigger(_ feedbackType: HapticFeedbackType) {<br>        // Do not trigger feedback if Low Power Mode is enabled<br>        if ProcessInfo.processInfo.isLowPowerModeEnabled { return }<br><br>        DispatchQueue.main.async { [weak self] in<br>            guard let self else { return }<br><br>            switch feedbackType {<br>            case .light:<br>                self.lightImpactGenerator.impactOccurred()<br>            case .medium:<br>                self.mediumImpactGenerator.impactOccurred()<br>            case .heavy:<br>                self.heavyImpactGenerator.impactOccurred()<br>            case .soft:<br>                self.softImpactGenerator?.impactOccurred()<br>            case .rigid:<br>                self.rigidImpactGenerator?.impactOccurred()<br>            case .success:<br>                self.notificationGenerator.notificationOccurred(.success)<br>            case .warning:<br>                self.notificationGenerator.notificationOccurred(.warning)<br>            case .error:<br>                self.notificationGenerator.notificationOccurred(.error)<br>            }<br><br>            // Prepare generators again for subsequent use<br>            self.prepareAllGenerators()<br>        }<br>    }<br>}</pre><p>Haptic feedback may be restricted when low power mode is active. If you want further control, you can check this with ProcessInfo :</p><pre>if ProcessInfo.processInfo.isLowPowerModeEnabled {<br>    // No triggering in low power mode<br>    return<br>}</pre><h3>Usage Examples in a ViewController</h3><h4>1. Triggering Success Feedback</h4><pre>HapticFeedbackManager.shared.trigger(.success)</pre><h4>2. Triggering Warning Feedback</h4><pre>HapticFeedbackManager.shared.trigger(.warning)</pre><h4>3. Implementing Feedback in a Button Action</h4><p>Below is a complete example integrating haptic feedback with a UIButton:</p><pre>import UIKit<br><br>class ViewController: UIViewController {<br>    private let feedbackButton: UIButton = {<br>        let button = UIButton(type: .system)<br>        button.setTitle(&quot;Trigger Haptic&quot;, for: .normal)<br>        button.backgroundColor = .systemBlue<br>        button.setTitleColor(.white, for: .normal)<br>        button.layer.cornerRadius = 8<br>        button.translatesAutoresizingMaskIntoConstraints = false<br>        return button<br>    }()<br><br>    override func viewDidLoad() {<br>        super.viewDidLoad()<br>        view.backgroundColor = .white<br>        view.addSubview(feedbackButton)<br><br>        feedbackButton.addTarget(self, action: #selector(feedbackButtonTapped), for: .touchUpInside)<br><br>        NSLayoutConstraint.activate([<br>            feedbackButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),<br>            feedbackButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),<br>            feedbackButton.widthAnchor.constraint(equalToConstant: 160),<br>            feedbackButton.heightAnchor.constraint(equalToConstant: 50)<br>        ])<br>    }<br><br>    @objc private func feedbackButtonTapped() {<br>        // Trigger heavy haptic feedback<br>        HapticFeedbackManager.shared.trigger(.heavy)<br>    }<br>}</pre><h3>Best Practices</h3><ol><li><strong>Contextual Feedback:</strong> Ensure the feedback type matches the context. Avoid unnecessary vibrations that could irritate users.</li><li><strong>Performance Optimization:</strong> Always prepare feedback generators using prepare() to minimize delays.</li><li><strong>Low Power Mode Handling:</strong> Respect the user’s device settings by skipping feedback when Low Power Mode is enabled.</li></ol><h3>Conclusion</h3><p>Haptic feedback adds a layer of physical interactivity that can significantly enhance the user experience. By implementing a centralized manager like HapticFeedbackManager, you can streamline its use across your app and ensure consistent, meaningful feedback for users.</p><p>Using haptic feedback effectively can make your app more engaging and intuitive. Ensure that every feedback serves a purpose and aligns with the user’s expectations.</p><p>Looking forward to seeing you in the next post. Take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cb0a997a0e7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern iOS Application Development with SwiftUI: A Developer’s Perspective]]></title>
            <link>https://medium.com/@burakekmen/modern-ios-application-development-with-swiftui-a-developers-perspective-865ae04cdc23?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/865ae04cdc23</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Sat, 14 Sep 2024 22:33:51 GMT</pubDate>
            <atom:updated>2024-09-14T22:37:59.725Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frLkX4rVa2sH_tsCfym5QQ.png" /></figure><p>When SwiftUI was announced in 2019, it marked a transformative step in the iOS development paradigm. Apple’s new framework introduces a declarative programming model, making interface development simpler, more flexible, and easier to read. As a senior developer, it is crucial to pay attention to both performance optimizations and architectural decisions to leverage the full potential of SwiftUI efficiently. In this article, we will cover a broad range of topics, from the fundamental concepts of SwiftUI to performance enhancements, and how architectural patterns can be adapted to SwiftUI.</p><h3><strong>Declarative Programming: The Future of Interfaces</strong></h3><p>When <strong>working</strong> <strong>with UIKit</strong>, we are often used to writing code in an <strong>imperative style</strong>. For example, we <strong>write specific code to update a view</strong> when a button is pressed. However, <strong>SwiftUI</strong> follows a <strong>completely different</strong> paradigm: <strong>declarative programming</strong>.</p><p><strong>Declarative programming</strong> defines <strong>how a user interface should look</strong>. In this model, you update the state of a component, and <strong>the interface re-renders itself</strong> based on that state. For instance, if you want to show the character count of what the user types into a text field in real-time, you would directly use an interactive Text component:</p><pre>@State private var textInput = &quot;&quot;<br><br>var body: some View {<br>    VStack {<br>        TextField(&quot;Type something&quot;, text: $textInput)<br>        Text(&quot;Character count: \(textInput.count)&quot;)<br>    }<br>}</pre><p>Switching to this style of coding can shift the way you think, particularly about <strong>state management</strong> and <strong>data flow</strong>. Since SwiftUI updates the screen based on state-driven refreshes, it becomes crucial to manage the state accurately.</p><h4><strong>Imperative vs. Declarative Comparison</strong></h4><p>In <strong>the old imperative approach</strong>, we would write code like this:</p><pre>func updateLabelText() {<br>    if count &gt; 10 {<br>        label.text = &quot;More than 10!&quot;<br>    } else {<br>        label.text = &quot;Less than 10!&quot;<br>    }<br>}</pre><p><strong>With SwiftUI</strong>, we can make this much more <strong>concise</strong> and <strong>readable</strong>:</p><pre>var body: some View {<br>    Text(count &gt; 10 ? &quot;More than 10!&quot; : &quot;Less than 10!&quot;)<br>}</pre><p>Even this simple example shows how <strong>declarative programming</strong> simplifies code. Instead of focusing on how the screen should update, we now <strong>describe what it is</strong>.</p><h3><strong>State Management with @State, @Binding, and @ObservedObject</strong></h3><p>In SwiftUI, <strong>state management is a crucial topic</strong> that requires close attention. By using property wrappers like <strong>@State, @Binding</strong>, and <strong>@ObservedObject</strong>, you control how <strong>state changes are reflected in the UI</strong>. As a senior developer, here are a few key points to consider when implementing these concepts:</p><p>a) <strong>@State</strong>: Typically used to manage local state within a <strong>View</strong>. Views should be lightweight and simple; avoid placing complex business logic in them.</p><p>Let’s look at an example of a simple counter application:</p><pre>struct CounterView: View {<br>    @State private var count: Int = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Counter: \(count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br>            <br>            Button(&quot;Increase&quot;) {<br>                count += 1<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><p>In this example, the count variable defined with <strong>@State</strong> is stored locally within the view. Each time the &quot;Increase&quot; button is pressed, count is updated, and SwiftUI <strong>re-renders</strong> the UI accordingly. However, <strong>@State</strong> can only be used within the view it is declared. To pass this state to another view, we need to use <strong>@Binding</strong>.</p><p>b) <strong>@Binding</strong>: This is used when we want to access and modify the state of one view from another view. By passing a state managed by <strong>@State</strong> to child views using <strong>@Binding</strong>, we <strong>can synchronize</strong> the state between two views.</p><p>In the following example, you can see how we pass the state from CounterView to another view using @Binding:</p><pre>struct ParentView: View {<br>    @State private var count: Int = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Parent Counter: \(count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br><br>            ChildView(count: $count)  // Passing state to the child view using Binding.<br>        }<br>    }<br>}<br><br>struct ChildView: View {<br>    @Binding var count: Int<br><br>    var body: some View {<br>        Button(&quot;Increase from Child&quot;) {<br>            count += 1<br>        }<br>        .padding()<br>    }<br>}</pre><p>In this example:</p><ul><li>ParentView manages the count using <strong>@State</strong>.</li><li>ChildView accesses and modifies the count passed from ParentView using <strong>@Binding</strong>.</li></ul><p>This structure shares the parent view’s state with the child view, ensuring <strong>synchronization</strong>. Both views share the same count state, and any change in one view is <strong>instantly reflected</strong> in the other.</p><p>c) <strong>@ObservedObject</strong>: This is used when a view needs to observe the state defined in another class. If the properties of this class are marked with <strong>@Published</strong>, any changes to these properties <strong>will automatically be observed</strong> by SwiftUI, <strong>triggering</strong> a UI update.</p><p>Let’s demonstrate this with a <strong>ViewModel</strong> structure:</p><pre>class CounterViewModel: ObservableObject {<br>    @Published var count: Int = 0<br><br>    func increment() {<br>        count += 1<br>    }<br>}<br><br>struct ViewWithViewModel: View {<br>    @ObservedObject var viewModel = CounterViewModel()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Counter: \(viewModel.count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br><br>            Button(&quot;Increase&quot;) {<br>                viewModel.increment()<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><p>In this example:</p><ul><li>CounterViewModel is defined according to the <strong>ObservableObject</strong> protocol, and the count variable is marked with <strong>@Published</strong>. This ensures that SwiftUI gets notified whenever the count changes.</li><li>ViewWithViewModel observes the CounterViewModel using @ObservedObject. When any change occurs, SwiftUI <strong>automatically re-renders </strong>the interface.</li></ul><h3><strong>View Lifecycle: A Different Approach from UIKit</strong></h3><p>In <strong>UIKit</strong>, we are used to lifecycle methods like <strong>viewDidLoad</strong> and <strong>viewWillAppear</strong>. However, <strong>SwiftUI</strong> <strong>doesn’t have</strong> such methods because everything is state-driven. SwiftUI views can be thought of as static structures, but they are entirely recreated whenever there is a state change. This may seem concerning in terms of performance, but SwiftUI efficiently manages this process—only the necessary parts are re-rendered.</p><h4><strong>How Does View Lifecycle Work in SwiftUI?</strong></h4><p>In SwiftUI, the lifecycle of a view is based on being re-created according to state changes. <strong>SwiftUI</strong> <strong>automatically recreates the view every time</strong> the state changes. As a result, the view’s lifecycle is not a controlled flow but rather a continuous refresh cycle.</p><p>In this cycle, fundamentally:</p><ul><li><strong>When the View is Created for the First Time</strong>: SwiftUI processes the body of the view for the first time, and the view is rendered on the screen.</li><li><strong>As the State Changes</strong>: When the state (such as <strong>@State</strong>, <strong>@ObservedObject</strong> property wrappers) changes, SwiftUI re-renders the view that depends on that state. This causes the view to be redrawn.</li><li><strong>When the View is Destroyed</strong>: If the view is removed (for example, through navigation), SwiftUI deallocates the view from memory.</li></ul><p>There are several ways to observe the view lifecycle in SwiftUI:</p><ul><li><strong>onAppear</strong>: Called when a view becomes visible.</li><li><strong>onDisappear</strong>: Called when a view disappears.</li><li><strong>task</strong>: A modifier provided by SwiftUI to start an asynchronous task. This task is triggered when the view becomes visible.</li></ul><h4><strong>View Lifecycle Methods</strong></h4><p><strong>onAppear</strong><br><strong>onAppear</strong> is triggered when a <strong>view becomes visible</strong> on the screen in SwiftUI. This method is typically used to perform actions that need to happen <strong>when a view is loaded</strong>.</p><pre>struct ContentView: View {<br>    @State private var isLoaded = false<br><br>    var body: some View {<br>        Text(isLoaded ? &quot;View Loaded&quot; : &quot;Loading...&quot;)<br>            .onAppear {<br>                // Triggered when the view appears<br>                isLoaded = true<br>                print(&quot;View appeared on screen!&quot;)<br>            }<br>    }<br>}</pre><p>In this example, the <strong>onAppear</strong> modifier is used to perform an action when <strong>the view is loaded</strong>. The <strong>isLoaded</strong> variable is set to true, causing the text to update.</p><p><strong>onDisappear</strong><br><strong>onDisappear</strong> is triggered <strong>when a view disappears</strong> from the screen. This method is often used for cleanup operations <strong>when a view is dismissed</strong>.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;View is Open&quot;)<br>            .onDisappear {<br>                // Triggered when the view disappears<br>                print(&quot;View disappeared from the screen!&quot;)<br>            }<br>    }<br>}</pre><p>In this example, <strong>onDisappear</strong> is <strong>triggered when the view is removed</strong>, allowing for any necessary cleanup to be performed.</p><p><strong>task</strong><br>The <strong>task</strong> method is used to start an <strong>asynchronous task</strong> when a view becomes visible in SwiftUI. For instance, you can use <strong>task</strong> to make an API call to load data when the view is displayed.</p><pre>struct ContentView: View {<br>    @State private var data: String = &quot;Loading...&quot;<br><br>    var body: some View {<br>        Text(data)<br>            .task {<br>                await loadData()<br>            }<br>    }<br><br>    // Asynchronous data loading function<br>    func loadData() async {<br>        // Simulate an API call<br>        try? await Task.sleep(nanoseconds: 2 * 1_000_000_000) // Wait for 2 seconds<br>        data = &quot;Data loaded!&quot;<br>    }<br>}</pre><p>In this example, the <strong>task</strong> modifier is used to call the <strong>loadData()</strong> function, and after a 2-second delay, the data displayed on the screen is updated.</p><p><strong>Difference in View Lifecycle from UIKit</strong><br>In SwiftUI, views are continuously recreated within a lifecycle loop, which means there are <strong>no direct</strong> lifecycle methods like <strong>viewDidLoad</strong>, <strong>viewWillAppear</strong>, or <strong>viewDidDisappear</strong> <strong>as in UIKit</strong>. Instead, <strong>SwiftUI</strong> performs state-driven re-rendering, and methods such as <strong>onAppear</strong> and <strong>onDisappear</strong> are used to track the view&#39;s lifecycle during these re-render processes.</p><h3><strong>Performance Optimizations and the View Body Function</strong></h3><p>SwiftUI uses a <strong>diffing algorithm</strong> to <strong>re-render only the views</strong> that have changed. However, even seemingly small changes can sometimes lead to performance issues. As senior developers, understanding how views are rendered becomes critical. Since the <strong>body</strong> function in <strong>SwiftUI</strong> is <strong>called with every change</strong>, it’s important to keep the content of this function as simple as possible to maintain performance. Additionally, improper use of properties like <strong>@State</strong> and <strong>@ObservedObject</strong> can lead to unwanted render operations.</p><pre>struct ContentView: View {<br>    @ObservedObject var viewModel = MyViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Counter: \(viewModel.count)&quot;)<br>            Button(&quot;Increase&quot;, action: {<br>                viewModel.increment()<br>            })<br>        }<br>    }<br>}</pre><p><strong>Note:</strong> When working with lists, you might notice that methods like <strong>onAppear</strong> are called frequently. To minimize such occurrences, prefer performance-focused views like <strong>LazyVStack</strong>.</p><h3><strong>The Power of Combine and SwiftUI: Reactive Programming</strong></h3><p>As a senior developer, if you’re familiar with the principles of reactive programming, you’ll find that <strong>Combine</strong> creates a <strong>wonderful synergy</strong> with <strong>SwiftUI</strong>. Making SwiftUI’s interface reactive with Combine’s <strong>Publisher</strong> structure allows you to respond to current data streams in a more natural and clean way.</p><pre>import Combine<br><br>class DataFetcher: ObservableObject {<br>    @Published var data: [String] = []<br>    private var cancellable: AnyCancellable?<br>    <br>    init() {<br>        fetchData()<br>    }<br>    <br>    func fetchData() {<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!<br>        cancellable = URLSession.shared.dataTaskPublisher(for: url)<br>            .map { $0.data }<br>            .decode(type: [String].self, decoder: JSONDecoder())<br>            .receive(on: DispatchQueue.main)<br>            .sink(receiveCompletion: { _ in }, receiveValue: { [weak self] in self?.data = $0 })<br>    }<br>}</pre><p>By combining the power of <strong>Combine</strong> with <strong>SwiftUI</strong>, you can manage how your user interface responds to asynchronous data streams in an extremely effective way.</p><h3><strong>Architectural Approach in SwiftUI: MVVM Implementation</strong></h3><p>As a senior developer, our architectural choices directly impact the success of a project. <strong>SwiftUI</strong> works exceptionally well with the <strong>MVVM</strong> (Model-View-ViewModel) architecture. SwiftUI views should be responsible only for reflecting data on the screen; <strong>business logic should be kept in the ViewModel.</strong></p><p>Here is a simple MVVM example:</p><pre>// Model<br>struct Todo: Identifiable {<br>    let id = UUID()<br>    let title: String<br>    let isCompleted: Bool<br>}<br><br>// ViewModel<br>class TodoViewModel: ObservableObject {<br>    @Published var todos: [Todo] = []<br>    <br>    func addTodo() {<br>        todos.append(Todo(title: &quot;New Task&quot;, isCompleted: false))<br>    }<br>}<br><br>// View<br>struct TodoListView: View {<br>    @ObservedObject var viewModel = TodoViewModel()<br><br>    var body: some View {<br>        List(viewModel.todos) { todo in<br>            Text(todo.title)<br>        }<br>        Button(&quot;Add New Task&quot;, action: viewModel.addTodo)<br>    }<br>}</pre><p><strong>Things to Consider in MVVM:</strong></p><ul><li><strong>Single Source of Truth:</strong> Each view <strong>should be</strong> fed by only one ViewModel. If state management becomes complex, organizing the ViewModel layer is the best approach to reduce this complexity.</li><li><strong>@Published and Reactivity:</strong> State updates <strong>should be</strong> tracked reactively. Managing publishers effectively with <strong>Combine</strong> can enhance the application’s performance.</li></ul><h3><strong>SwiftUI Lists and Performance</strong></h3><p>Lists are a <strong>crucial component</strong> in SwiftUI, especially when dealing with collections of data. However, when managing large datasets, performance can become a concern. <strong>SwiftUI</strong> offers powerful mechanisms to handle these scenarios efficiently, such as <strong>LazyVStack</strong> and <strong>LazyHStack</strong>, which <strong>help optimize performance</strong> similarly to <strong>UITableView</strong> or <strong>UICollectionView</strong> in UIKit.</p><h4>Key Concepts:</h4><ol><li><strong>Lazy Loading</strong>:</li></ol><p>SwiftUI’s <strong>List</strong>, <strong>LazyVStack</strong>, and <strong>LazyHStack</strong> use lazy loading techniques, meaning<strong> they only create and render the views</strong> that are currently visible on the screen. As you scroll through the list, <strong>only the cells</strong> in view are <strong>rendered</strong>, which significantly reduces the memory footprint and improves performance.</p><p><strong>2. Avoiding Unnecessary Renders</strong>:</p><p>SwiftUI uses a <strong>diffing algorithm</strong> to efficiently manage view updates. When the state changes, <strong>SwiftUI</strong> compares the old and new view states and <strong>updates only the parts of the view</strong> hierarchy that have changed. This <strong>minimizes</strong> the amount of work required to <strong>redraw</strong> the UI.</p><h4>Best Practices for List Performance:</h4><ol><li><strong>Using Identifiable</strong>:</li></ol><p>For optimal performance, ensure that each item in your list conforms to the <strong>Identifiable</strong> protocol. This requires each item to have a <strong>unique identifier (</strong><strong>id)</strong>. SwiftUI relies on this identifier to <strong>efficiently track</strong> and <strong>manage list items</strong> during updates. <strong>Without</strong> unique identifiers, SwiftUI <strong>may need to recreate </strong>the entire list on each render, which <strong>can be costly</strong> in terms of performance.</p><pre>struct Item: Identifiable {<br>    let id = UUID() // Unique identifier<br>    let title: String<br>}</pre><p><strong>2. Efficient Data Fetching</strong>:</p><ul><li>When dealing with large datasets, it’s essential to load data efficiently. Utilize <strong>onAppear</strong> to trigger data loading or operations when specific cells come into view. This way, you can fetch data as needed instead of loading everything upfront.</li></ul><pre>struct ContentView: View {<br>    @State private var items: [Item] = []<br><br>    var body: some View {<br>        List(items) { item in<br>            Text(item.title)<br>                .onAppear {<br>                    // Load additional data when this item appears<br>                }<br>        }<br>    }<br>}</pre><p><strong>3. Use of </strong><strong>LazyVStack and </strong><strong>LazyHStack</strong>:</p><p>For scenarios where you’re <strong>not</strong> using <strong>List</strong>, <strong>LazyVStack</strong> and <strong>LazyHStack</strong> are <strong>excellent alternatives</strong>. They provide similar lazy loading capabilities and are particularly useful for custom layouts where you need to manage large collections of views efficiently.</p><pre>struct ContentView: View {<br>    let items: [Item]<br><br>    var body: some View {<br>        ScrollView {<br>            LazyVStack {<br>                ForEach(items) { item in<br>                    Text(item.title)<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>4. Handling Heavy Operations</strong>:</p><p>Avoid performing heavy computations directly within your views. Instead, offload such <strong>tasks to background threads</strong> or <strong>pre-process data</strong>. This helps keep the <strong>main thread free</strong> and <strong>responsive</strong>, ensuring smooth scrolling and interactions.</p><h3><strong>Custom Animations: The Most Fun Aspect of SwiftUI</strong></h3><p>Animating with SwiftUI is easier and more impressive than ever. By simply changing the state within a <strong>withAnimation</strong> block, animations are <strong>automatically</strong> triggered.</p><pre>@State private var isAnimating = false<br><br>var body: some View {<br>    VStack {<br>        Circle()<br>            .frame(width: isAnimating ? 100 : 50, height: isAnimating ? 100 : 50)<br>            .animation(.easeInOut(duration: 0.5), value: isAnimating)<br>        <br>        Button(&quot;Start Animation&quot;) {<br>            isAnimating.toggle()<br>        }<br>    }<br>}</pre><p>With the different animation options provided by SwiftUI, you can enrich the user experience in your app. Especially with <strong>spring</strong> and <strong>timing curve</strong> animations, you can achieve more natural transitions.</p><pre>.animation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 1))</pre><p>You can use animations to draw users’ attention or highlight important events, <strong>but</strong> be cautious not to overuse them.</p><p><strong>SwiftUI</strong> is considered the <strong>UI framework of the future</strong>. Apple’s investment and advancements in this technology suggest that <strong>SwiftUI will dominate</strong> in the long run. As senior developers, there are many details we need to pay attention to during the transition to this new paradigm. However, by using the right techniques and best practices, it’s possible to leverage SwiftUI’s capabilities to develop modern, flexible, and high-performance iOS applications.</p><p>See you in the next post. Take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=865ae04cdc23" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[(TR) SwiftUI ile Modern iOS Uygulama Geliştirme: Geliştirici Perspektifi]]></title>
            <link>https://medium.com/@burakekmen/tr-swiftui-ile-modern-ios-uygulama-geli%C5%9Ftirme-geli%C5%9Ftirici-perspektifi-cd2a31e13dbb?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd2a31e13dbb</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Fri, 13 Sep 2024 14:02:47 GMT</pubDate>
            <atom:updated>2024-09-13T14:02:47.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJfntE_xJyAHX-b7PzQfJw.png" /></figure><p>SwiftUI, 2019&#39;da duyurulduğunda, iOS uygulama geliştirme paradigmasını değiştiren bir adım oldu. Apple’ın bu yeni çerçevesi, deklaratif bir programlama modeli sunarak arayüz geliştirmeyi daha sade, esnek ve okunabilir hale getiriyor. Senior bir geliştirici olarak, SwiftUI’nın sağladığı avantajları maksimum verimlilikle kullanmak için hem performans optimizasyonlarına hem de mimari kararlara dikkat etmek gerekiyor. Bu yazıda, SwiftUI’nın temel kavramlarından performans iyileştirmelerine, mimari yapıların SwiftUI’ya nasıl adapte edilebileceğine kadar geniş bir yelpazede konuları ele alacağız.</p><h3>Deklaratif Programlama: Arayüzün Geleceği</h3><p>UIKit ile çalışırken çoğu zaman imperatif bir tarzda kod yazmaya alışığızdır. Örneğin, bir düğmeye basıldığında bir görünümü güncellemek için spesifik kodlar yazarız. Ancak SwiftUI, tamamen farklı bir paradigmaya sahiptir: <strong>deklaratif programlama</strong>.</p><p>Deklaratif programlama, bir kullanıcı arayüzünün <strong>nasıl</strong> görünmesi gerektiğini tanımlar. Bu modelde, bir bileşen durumunu güncellersiniz ve arayüz, duruma göre kendini yeniden oluşturur. Örneğin, bir metin alanında kullanıcının yazdığı karakter sayısını güncel olarak göstermek istediğimizde, direkt olarak etkileşimli bir Text bileşeni kullanırız:</p><pre>@State private var textInput = &quot;&quot;<br><br>var body: some View {<br>    VStack {<br>        TextField(&quot;Bir şeyler yazın&quot;, text: $textInput)<br>        Text(&quot;Karakter Sayısı: \(textInput.count)&quot;)<br>    }<br>}</pre><p>Bu tarz kodlamaya geçiş, özellikle <strong>state management</strong> ve <strong>data flow</strong> konularında düşünme biçiminizi değiştirebilir. SwiftUI, duruma dayalı yenilemelerle ekranı güncellediği için, mutlak doğrulukla durumu yönetmek çok önemli hale gelir.</p><h4>Imperatif ve Deklaratif Karşılaştırması</h4><p>Eski imperatif yaklaşımda şöyle bir kod yazıyorduk:</p><pre>func updateLabelText() {<br>    if count &gt; 10 {<br>        label.text = &quot;10&#39;dan fazla!&quot;<br>    } else {<br>        label.text = &quot;10&#39;dan az!&quot;<br>    }<br>}</pre><p>SwiftUI ile bunu çok daha kısa ve okunabilir bir hale getiriyoruz:</p><pre>var body: some View {<br>    Text(count &gt; 10 ? &quot;10&#39;dan fazla!&quot; : &quot;10&#39;dan az!&quot;)<br>}</pre><p>Bu basit örnek bile deklaratif programlamanın kodu ne kadar sadeleştirdiğini gösteriyor. Artık ekranın nasıl güncellenmesi gerektiğiyle değil, <strong>ne olduğunu</strong> tarif ediyoruz.</p><h3>@State, @Binding, ve @ObservedObject İle State Yönetimi</h3><p>SwiftUI’da state yönetimi başlı başına dikkat edilmesi gereken bir konu. <strong>@State</strong>, <strong>@Binding</strong>, ve <strong>@ObservedObject</strong> gibi property wrapper’ları kullanarak durum değişikliklerinin arayüzde nasıl yankı bulduğunu kontrol edersiniz. Bu kavramları senior bir geliştirici olarak uygulamaya geçirirken şu noktalara dikkat etmenizi öneririm:</p><p><strong>a) @State</strong>: Genellikle bir View içinde yerel durumları yönetmek için kullanılır. View’lar hafif ve basit olmalıdır; karmaşık iş mantığını buraya koymaktan kaçının.</p><p>Örnek bir sayaç uygulaması üzerinden bakalım:</p><pre>struct CounterView: View {<br>    @State private var count: Int = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Sayaç: \(count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br>            <br>            Button(&quot;Arttır&quot;) {<br>                count += 1<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><p>Bu örnekte, @State ile tanımlanan count değişkeni, view içinde lokal olarak saklanır. &quot;Arttır&quot; butonuna her basıldığında count güncellenir ve SwiftUI bu güncellemeye göre UI’ı yeniden render eder. Ancak, @State sadece view içinde kullanılabilir, başka bir view’a bu durumu geçmek için <strong>@Binding</strong> kullanmamız gerekir.</p><p><strong>b) @Binding</strong>: Bir view’da başka bir view’ın state’ine erişmek ve o state’i değiştirmek istediğimizde kullanılır. <strong>@State</strong> ile yönetilen bir durumu, alt view’lara aktararak iki view arasında senkronizasyon sağlayabiliriz.</p><p>Aşağıdaki örnekte, CounterView’dan başka bir view’a @Binding ile durumu nasıl geçirdiğimizi görebiliriz:</p><pre>struct ParentView: View {<br>    @State private var count: Int = 0<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Parent Sayaç: \(count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br><br>            ChildView(count: $count)  // Binding kullanarak child view&#39;a state&#39;i geçiyoruz.<br>        }<br>    }<br>}<br><br>struct ChildView: View {<br>    @Binding var count: Int<br><br>    var body: some View {<br>        Button(&quot;Child&#39;dan Arttır&quot;) {<br>            count += 1<br>        }<br>        .padding()<br>    }<br>}</pre><p>Bu örnekte:</p><ul><li>ParentView, <strong>@State</strong> ile count’ı yönetiyor.</li><li>ChildView, @Binding ile ParentView&#39;den gelen count&#39;a erişiyor ve bu değeri değiştiriyor.</li></ul><p>Bu yapı, üst view’ın state’ini alt view ile paylaşarak senkronizasyon sağlıyor. Her iki view da aynı count state&#39;ini paylaşır ve bir view’da yapılan değişiklik diğer view’da anında yansır.</p><p><strong>c) @ObservedObject</strong>: Bir view’ın başka bir sınıfta tanımlı durumları takip etmesi için kullanılır. Bu sınıfın özellikleri <strong>@Published</strong> ile işaretlenirse, bu özelliklerdeki değişiklikler SwiftUI tarafından otomatik olarak gözlemlenir ve arayüz güncellenir.</p><p>Bir ViewModel yapısı ile bunu örneklendirelim:</p><pre>class CounterViewModel: ObservableObject {<br>    @Published var count: Int = 0<br><br>    func increment() {<br>        count += 1<br>    }<br>}<br><br>struct ViewWithViewModel: View {<br>    @ObservedObject var viewModel = CounterViewModel()<br><br>    var body: some View {<br>        VStack {<br>            Text(&quot;Sayaç: \(viewModel.count)&quot;)<br>                .font(.largeTitle)<br>                .padding()<br><br>            Button(&quot;Arttır&quot;) {<br>                viewModel.increment()<br>            }<br>            .padding()<br>        }<br>    }<br>}</pre><p>Bu örnekte:</p><ul><li>CounterViewModel, <strong>ObservableObject</strong> protokolüne uygun şekilde tanımlandı ve içindeki count değişkeni <strong>@Published</strong> ile işaretlendi. Bu, her count değiştiğinde SwiftUI’a bildirim yapılmasını sağlar.</li><li>ViewWithViewModel, @ObservedObject ile CounterViewModel&#39;ı izler. Herhangi bir değişiklik olduğunda, SwiftUI arayüzü otomatik olarak yeniden oluşturur.</li></ul><h3>View Lifecycle: UIKit’ten Farklı Bir Yaklaşım</h3><p>UIKit’in viewDidLoad, viewWillAppear gibi lifecycle metotlarına alışkınız. Ancak SwiftUI, bu tarz yöntemlere sahip değil çünkü her şey duruma dayalı. SwiftUI View’ları statik yapılar olarak düşünülebilir, fakat her durum değişikliğinde SwiftUI View&#39;ı tamamen yeniden oluşturur. Bu, performans açısından endişe verici görünebilir, ancak aslında SwiftUI’nın bu süreci verimli bir şekilde yönettiğini bilmelisiniz. Sadece gerekli olan kısımlar yeniden oluşturulur.</p><h4>SwiftUI’da View Lifecycle Nasıl İşler?</h4><p>SwiftUI’da bir view’ın lifecycle’ı, duruma göre yeniden oluşturulmaya dayalıdır. SwiftUI, view’ı her state değişikliğinde otomatik olarak yeniden yaratır, bu nedenle view’ın yaşam döngüsü bir kontrol akışı değil, sürekli bir yenilenme döngüsüdür.</p><p>Bu döngüde temel olarak:</p><ol><li><strong>View İlk Defa Oluşturulduğunda</strong>: SwiftUI, view’ı tanımlayan body’i ilk kez işler ve görünüm ekran üzerinde çizilir.</li><li><strong>State Değiştikçe</strong>: State (örneğin, @State, @ObservedObject gibi property wrapper’lar) değiştiğinde, SwiftUI o state’e bağlı view’ı yeniden render eder. Bu işlem, view’ın yeniden çizilmesine neden olur.</li><li><strong>View Yok Edildiğinde</strong>: View ortadan kalkarsa (örneğin bir navigation işlemiyle), SwiftUI view’ı bellekten kaldırır.</li></ol><p>SwiftUI’da view lifecycle’ı izlemek için birkaç yöntem vardır:</p><ul><li><strong>onAppear</strong>: Bir view görünür hale geldiğinde çağrılır.</li><li><strong>onDisappear</strong>: Bir view kaybolduğunda çağrılır.</li><li><strong>task</strong>: SwiftUI’nın bir asenkron işlem başlatmak için sunduğu bir modifier’dır. View görünür hale gelirken bu işlem tetiklenir.</li></ul><h4>View Lifecycle Metodları</h4><h4>onAppear</h4><p>onAppear, SwiftUI’da bir view’ın ekranda görünür hale geldiği an tetiklenir. Bu metod genellikle, bir view yüklendiğinde yapılması gereken işlemler için kullanılır.</p><pre>struct ContentView: View {<br>    @State private var isLoaded = false<br><br>    var body: some View {<br>        Text(isLoaded ? &quot;View Yüklendi&quot; : &quot;Yükleniyor...&quot;)<br>            .onAppear {<br>                // View görünür olduğunda tetiklenir<br>                isLoaded = true<br>                print(&quot;View ekranda göründü!&quot;)<br>            }<br>    }<br>}</pre><p>Bu örnekte, onAppear kullanılarak view yüklendiğinde bir işlem yapılır. isLoaded değişkeni true&#39;ya ayarlanır ve bu sayede text güncellenir.</p><h4>onDisappear</h4><p>onDisappear, bir view ekrandan kaybolduğunda tetiklenir. Bu metod genellikle, bir view kapatıldığında yapılması gereken temizleme işlemleri için kullanılır.</p><pre>struct ContentView: View {<br>    var body: some View {<br>        Text(&quot;View Açık&quot;)<br>            .onDisappear {<br>                // View kaybolduğunda tetiklenir<br>                print(&quot;View ekrandan kayboldu!&quot;)<br>            }<br>    }<br>}</pre><p>Bu örnekte, onDisappear view ortadan kalktığında tetiklenir ve bu sayede gerekli temizlik işlemleri yapılabilir.</p><h4>task</h4><p>task metodu, SwiftUI&#39;da bir view görünür hale gelirken asenkron bir görevi başlatmak için kullanılır. Örneğin, verileri yüklemek için bir API çağrısı yapılacaksa task kullanarak bunu gerçekleştirebiliriz.</p><pre>struct ContentView: View {<br>    @State private var data: String = &quot;Yükleniyor...&quot;<br><br>    var body: some View {<br>        Text(data)<br>            .task {<br>                await loadData()<br>            }<br>    }<br><br>    // Asenkron veri yükleme işlemi<br>    func loadData() async {<br>        // Bir API çağrısı simüle edelim<br>        try? await Task.sleep(nanoseconds: 2 * 1_000_000_000) // 2 saniye bekle<br>        data = &quot;Veri yüklendi!&quot;<br>    }<br>}</pre><p>Bu örnekte, task kullanarak loadData() fonksiyonu çağrılıyor ve 2 saniyelik bir gecikmeden sonra ekrandaki veri güncelleniyor.</p><h4>View Lifecycle’ın UIKit’ten Farkı</h4><p>SwiftUI’da view’lar bir lifecycle döngüsü içinde sürekli olarak yeniden oluşturuldukları için, UIKit’teki gibi doğrudan viewDidLoad, viewWillAppear, viewDidDisappear gibi net lifecycle metodları yoktur. Bunun yerine SwiftUI, duruma dayalı yeniden render işlemleri yapar ve bu işlemler sırasında view yaşam döngüsünü takip etmek için <strong>onAppear</strong>, <strong>onDisappear</strong> gibi yöntemler kullanılır.</p><h3>Performans Optimizasyonları ve View Body Fonksiyonu</h3><p>SwiftUI, <strong>diffing algorithm</strong> kullanarak sadece değiştirilmiş olan View’ları yeniden render eder. Ancak, bazen görünüşte küçük değişiklikler bile performans sorunlarına yol açabilir. Senior geliştiriciler olarak, View’ların nasıl render edildiğini anlamak kritik hale gelir. SwiftUI’da <strong>body</strong> fonksiyonu her değişiklikte çağrıldığı için, bu fonksiyonun içeriğini mümkün olduğunca basit tutmak performans açısından önemlidir. Ayrıca, <strong>@State</strong> ve <strong>@ObservedObject</strong> gibi property’leri yanlış kullanmak, istemediğiniz render işlemlerine neden olabilir.</p><pre>struct ContentView: View {<br>    @ObservedObject var viewModel = MyViewModel()<br>    <br>    var body: some View {<br>        VStack {<br>            Text(&quot;Counter: \(viewModel.count)&quot;)<br>            Button(&quot;Artır&quot;, action: {<br>                viewModel.increment()<br>            })<br>        }<br>    }<br>}</pre><p><strong>Not:</strong> Özellikle listelerle çalışırken, <strong>onAppear</strong> gibi metotların sıkça çağrıldığını görebilirsiniz. Bu durumları minimize etmek için <strong>LazyVStack</strong> gibi performans odaklı View’ları tercih edin.</p><h3>Combine ve SwiftUI’ın Gücü: Reactive Programming</h3><p>Senior bir geliştirici olarak reaktif programlama prensiplerine hakimseniz, Combine ile SwiftUI’nın harika bir sinerji oluşturduğunu fark edeceksiniz. SwiftUI’nın arayüzünü, Combine ile gelen <strong>Publisher</strong> yapısıyla reaktif hale getirmek, güncel veri akışlarına daha doğal ve temiz bir şekilde yanıt vermenizi sağlar.</p><pre>import Combine<br><br>class DataFetcher: ObservableObject {<br>    @Published var data: [String] = []<br>    private var cancellable: AnyCancellable?<br>    <br>    init() {<br>        fetchData()<br>    }<br>    <br>    func fetchData() {<br>        let url = URL(string: &quot;https://jsonplaceholder.typicode.com/posts&quot;)!<br>        cancellable = URLSession.shared.dataTaskPublisher(for: url)<br>            .map { $0.data }<br>            .decode(type: [String].self, decoder: JSONDecoder())<br>            .receive(on: DispatchQueue.main)<br>            .sink(receiveCompletion: { _ in }, receiveValue: { [weak self] in self?.data = $0 })<br>    }<br>}</pre><p>Combine’ın gücünü SwiftUI ile birleştirerek, kullanıcı arayüzünün asenkron veri akışına nasıl tepki vereceğini son derece etkili bir şekilde yönetebilirsiniz.</p><h3>SwiftUI’da Mimari Yaklaşım: MVVM Uygulaması</h3><p>Senior geliştirici olarak, mimari seçimlerimiz projenin başarısını doğrudan etkiler. SwiftUI, MVVM (Model-View-ViewModel) yapısıyla oldukça uyumlu çalışır. SwiftUI View’ları, sadece veriyi ekrana yansıtmaktan sorumlu olmalı; iş mantığı ise ViewModel’de tutulmalıdır.</p><p>Aşağıda basit bir MVVM örneği bulabilirsiniz:</p><pre>// Model<br>struct Todo: Identifiable {<br>    let id = UUID()<br>    let title: String<br>    let isCompleted: Bool<br>}<br><br>// ViewModel<br>class TodoViewModel: ObservableObject {<br>    @Published var todos: [Todo] = []<br>    <br>    func addTodo() {<br>        todos.append(Todo(title: &quot;Yeni Görev&quot;, isCompleted: false))<br>    }<br>}<br><br>// View<br>struct TodoListView: View {<br>    @ObservedObject var viewModel = TodoViewModel()<br><br>    var body: some View {<br>        List(viewModel.todos) { todo in<br>            Text(todo.title)<br>        }<br>        Button(&quot;Yeni Görev Ekle&quot;, action: viewModel.addTodo)<br>    }<br>}</pre><p><strong>MVVM’de Dikkat Edilmesi Gerekenler:</strong></p><ul><li><strong>Single Source of Truth</strong>: Her View sadece bir ViewModel’dan beslenmeli. Durum yönetimi karmaşık hale gelirse, bu karmaşıklığı azaltmak için ViewModel katmanını düzenlemek en iyi yaklaşımdır.</li><li><strong>@Published ve Reaktiflik</strong>: Durum güncellemeleri reaktif şekilde takip edilmeli. <strong>Combine</strong> kullanarak yayıncıları (publisher) etkili bir şekilde yönetmek, uygulamanın performansını artırır.</li></ul><h3>SwiftUI Listeleri ve Performans</h3><p>Listeler, SwiftUI’da en sık kullanılan View yapılarından biridir. Ancak büyük veri kümeleriyle çalışırken performans sorunları yaşayabilirsiniz. SwiftUI’daki <strong>LazyVStack</strong> ve <strong>LazyHStack</strong> gibi yapılandırmalar, UIKit’teki <strong>UITableView</strong> veya <strong>UICollectionView</strong> ile karşılaştırılabilir ve yüksek performans sunar. Listeler, verileri gerektiği zaman yükleyerek gereksiz render işlemlerini önler.</p><pre>List(viewModel.items) { item in<br>    Text(item.title)<br>}</pre><p><strong>List Performansı için İpuçları:</strong></p><ul><li><strong>Identifiable Kullanımı</strong>: Her elemanınızın benzersiz bir kimliği olduğundan emin olun. Aksi takdirde SwiftUI her render işleminde tüm listeyi baştan oluşturur.</li><li><strong>onAppear ve LazyVStack</strong>: Listeler içinde ağır işlemleri başlatırken, her görünümün ne zaman görünür olduğunu kontrol edin. Gereksiz yere tüm listeyi aynı anda yüklemek yerine, <strong>onAppear</strong> ile ihtiyaç duyulduğunda verileri çağırabilirsiniz.</li></ul><h3>Custom Animasyonlar: SwiftUI’nın En Eğlenceli Yönü</h3><p>SwiftUI ile animasyonlar her zamankinden daha kolay ve etkileyici. <strong>withAnimation</strong> bloğu içerisinde sadece durumu değiştirmeniz, otomatik olarak animasyonların tetiklenmesini sağlar.</p><pre>@State private var isAnimating = false<br><br>var body: some View {<br>    VStack {<br>        Circle()<br>            .frame(width: isAnimating ? 100 : 50, height: isAnimating ? 100 : 50)<br>            .animation(.easeInOut(duration: 0.5), value: isAnimating)<br>        <br>        Button(&quot;Animasyonu Başlat&quot;) {<br>            isAnimating.toggle()<br>        }<br>    }<br>}</pre><p>SwiftUI’nın sunduğu farklı animasyon seçenekleri sayesinde uygulamanızda kullanıcı deneyimini zenginleştirebilirsiniz. Özellikle <strong>spring</strong> ve <strong>timing curve</strong> animasyonlarıyla daha doğal geçişler sağlayabilirsiniz.</p><pre>.animation(.spring(response: 0.5, dampingFraction: 0.6, blendDuration: 1))</pre><p>Animasyonlarınızı, kullanıcıların dikkatini çekmek ya da önemli bir olayı vurgulamak için kullanabilirsiniz, ancak aşırıya kaçmamaya dikkat edin.</p><p>SwiftUI, geleceğin UI framework’ü olarak kabul ediliyor. Apple’ın bu teknolojiye yaptığı yatırım ve geliştirmeler, SwiftUI’nın uzun vadede baskın olacağını gösteriyor. Senior geliştiriciler olarak, bu yeni paradigmaya geçiş sürecinde dikkat etmemiz gereken birçok detay var. Ancak doğru tekniklerle ve en iyi pratiklerle SwiftUI’nın sunduğu olanakları verimli bir şekilde kullanarak modern, esnek ve performanslı iOS uygulamaları geliştirmek mümkün.</p><p>Bir sonraki yazıda görüşmek üzere. Kendinize iyi bakın!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd2a31e13dbb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Noncopyable Structs and Enums in Swift]]></title>
            <link>https://medium.com/@burakekmen/noncopyable-structs-and-enums-in-swift-25ace97dcae8?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/25ace97dcae8</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[copyable]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Mon, 09 Sep 2024 19:01:53 GMT</pubDate>
            <atom:updated>2024-09-09T19:01:53.193Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pFsAxS24k7ZzZFzCA-48fA.png" /></figure><p>With the release of Swift 5.9, one of the most remarkable additions to the language is noncopyable structs and enums. This feature enables us to manage large data structures more efficiently, safeguard critical resources, and optimize performance. Swift’s default copyable behavior for value types can sometimes lead to unwanted memory and performance issues. However, with noncopyable types, we can avoid unnecessary copying and improve performance.</p><p>In this article, we’ll dive into what noncopyable structs and enums are, why they are important, and in which situations they can be useful. We’ll also explore how to use them with plenty of examples.</p><h3>Why Are Noncopyable Types Important?</h3><p>In Swift, value types like structs and enums are <strong>copyable by default</strong>. This usually isn’t an issue for small data structures. However, when working with large data structures or single-owned resources, copying can result in serious performance costs.</p><p>I’ve personally encountered cases where I unintentionally copied data structures multiple times, leading to performance issues. Noncopyable types prevent unnecessary memory consumption and performance degradation by disallowing copy operations.</p><h4>Example: Let’s create a Resource struct and try copying it to multiple places:</h4><pre>@noncopyable<br>struct Resource {<br>    let id: Int<br>    var isActive: Bool<br><br>    init(id: Int) {<br>        self.id = id<br>        self.isActive = true<br>    }<br><br>    mutating func deactivate() {<br>        self.isActive = false<br>    }<br>}<br><br>var resource1 = Resource(id: 101)<br>var resource2 = resource1 // Error: &#39;Resource&#39; cannot be copied</pre><p>In the example above, Resource is marked as @noncopyable, meaning <strong>it can no longer be copied</strong>. This prevents the creation of multiple copies of a single resource, making data management safer.</p><h3>When Should You Use Noncopyable Types?</h3><p>Let’s explore a few scenarios where using noncopyable types can be beneficial:</p><h4>1. Working with Large Data Structures</h4><p>Copying large data structures can be quite expensive, especially in terms of performance. Every copy operation requires duplicating the entire data structure, which puts a significant load on both memory and the CPU. By preventing the copying of large data structures, we can achieve significant performance gains.</p><pre>@noncopyable<br>struct LargeData {<br>    var data: [Int] = Array(repeating: 0, count: 1000000)<br>}</pre><p>When trying to copy the LargeData struct, the Swift compiler will immediately warn me. This helps prevent unnecessary memory duplication and increases performance.</p><h4>2. Managing Critical System Resources</h4><p>Managing critical system resources like file handlers, network connections, or hardware resources is a delicate task. Accidentally <strong>creating multiple copies of these</strong> resources <strong>can lead to serious errors</strong>. Noncopyable types ensure that only one instance of a resource exists.</p><pre>@noncopyable<br>struct FileHandler {<br>    var fileDescriptor: Int<br>    var isOpen: Bool = true<br><br>    mutating func close() {<br>        self.isOpen = false<br>        print(&quot;File closed.&quot;)<br>    }<br>}<br><br>var file1 = FileHandler(fileDescriptor: 10)<br>var file2 = file1 // Error: &#39;FileHandler&#39; cannot be copied</pre><p>In this example, copying FileHandler results in an error. This prevents the file from being opened or closed multiple times, ensuring more secure resource management.</p><h4>3. Performance-Critical Applications</h4><p><strong>In performance-critical applications</strong> like graphics processing, game development, or data-intensive computations, avoiding <strong>unnecessary copies is crucial</strong>. <strong>Noncopyable</strong> types <strong>help boost performance</strong> by preventing unnecessary duplication.</p><h3>Working with Move Semantics</h3><p>While noncopyable types <strong>can’t be copied</strong>, they <strong>can still be moved</strong> using move semantics. This means <strong>we can transfer ownership of a value</strong>, but we <strong>can’t duplicate it</strong>. Once the value is moved, the original can no longer be used.</p><pre>func processResource(_ resource: __owned Resource) {<br>    print(&quot;Processing resource with id: \(resource.id)&quot;)<br>}<br><br>var resource = Resource(id: 102)<br>processResource(resource) // &#39;resource&#39; can no longer be used.</pre><p>In this example, the processResource function moves the Resource. After the transfer, any attempt to use the original resource will result in a compiler error, ensuring that the data is only owned in one place.</p><h3>Performance Gains</h3><p>Noncopyable types offer significant performance gains:</p><ul><li><strong>Reduced Memory Usage</strong>: By opting to move data instead of copying it, we avoid replicating large data structures in memory.</li><li><strong>Lower CPU Load</strong>: Every copy operation stresses the CPU. With noncopyable types, we eliminate this unnecessary load, resulting in faster operations.</li></ul><p>These improvements are particularly noticeable when working with large data sets or memory-intensive applications.</p><h3>Application Scenarios</h3><p>Here are a few key scenarios where noncopyable types can be beneficial:</p><h4>1. Memory-Intensive Applications</h4><p>In memory-heavy applications like data analysis, large-scale graphics computations, or high-performance gaming, using noncopyable types can provide significant advantages. Copying large amounts of data is avoided, directly impacting performance.</p><h4>2. Resource Management</h4><p>Noncopyable types <strong>ensure safe resource management</strong> in cases where resources like file systems, network connections, or hardware must have single ownership.</p><h4>3. Concurrent Programming</h4><p>In concurrent programming, copying a resource across multiple threads can cause issues. Noncopyable types prevent multiple threads from modifying the same resource, reducing the chance of errors.</p><p>Looking forward to seeing you in the next post. Take care!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25ace97dcae8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Displaying Notification Counts (Badge) on App Icons — Swift]]></title>
            <link>https://medium.com/@burakekmen/displaying-notification-counts-badge-on-app-icons-swift-b8aaaf1a26db?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8aaaf1a26db</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Wed, 06 Dec 2023 19:27:07 GMT</pubDate>
            <atom:updated>2023-12-06T19:27:07.329Z</atom:updated>
            <content:encoded><![CDATA[<h3>Displaying Notification Counts (Badge) on App Icons — Swift</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*KNATLjihcGS2M1ziTPznyA.png" /></figure><p>Hi everyone! In this article, we’ll discuss the display of notification counts on application icons, a feature commonly seen in our daily lives. Since this will be a brief post, let’s dive right in without wasting any time.</p><p>Notifications in the app can be represented on the icon by incrementing the badgeNumber field, which is often used to indicate unread message counts or other relevant information. You can easily achieve this with the following code snippet:</p><pre>DispatchQueue.main.async {<br>    UIApplication.shared.applicationIconBadgeNumber += 1<br>}</pre><p>When <strong>you want to reset or decrease the number</strong> within the badge, simply set the value to 0. If <strong>0 is entered</strong>, the <strong>badge will be removed</strong> from the application icon.</p><p>Feel free to adapt this code to fit your specific needs and enhance the user experience in your iOS applications. Happy coding!</p><p>Sample project on Github:</p><p><a href="https://github.com/burakekmen/AppBadgeCount">GitHub - burakekmen/AppBadgeCount</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8aaaf1a26db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Drag & Drop Uygulamak — DiffableCollectionView, UIKit]]></title>
            <link>https://medium.com/@burakekmen/drag-drop-uygulamak-diffablecollectionview-uikit-34bfc26f0e4a?source=rss-47c57757afd8------2</link>
            <guid isPermaLink="false">https://medium.com/p/34bfc26f0e4a</guid>
            <category><![CDATA[collectionview]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[drag-delegate]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[diffable-data-sources]]></category>
            <dc:creator><![CDATA[Burak EKMEN]]></dc:creator>
            <pubDate>Sat, 28 Jan 2023 21:22:35 GMT</pubDate>
            <atom:updated>2023-01-29T08:10:27.154Z</atom:updated>
            <content:encoded><![CDATA[<h3>Drag &amp; Drop Uygulamak — DiffableCollectionView, UIKit</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A-Ldf7EZm0tJV_OTTwSrKQ.png" /></figure><p>Bu makalemde DiffableCollectionView içerisinde Drag &amp; Drop hareketleri nasıl yapılır bundan bahsediyor olacağım. Şimdiden iyi okumalar dilerim.</p><p>Öncelikle <strong>makalenin ana odak noktası</strong> <strong>DiffableCollectionView</strong> anlatımı <strong>olmayacağı</strong> için makale içerisinde bu konuya girilmeyip bilindiği varsayılarak ilerleyeceğim. Aşağıdaki makaleden detaylı bilgilere ulaşabilirsiniz.</p><p><a href="https://www.appcoda.com/diffable-data-source/">Using Diffable Data Source with Collection Views</a></p><p>Sürükle &amp; Bırak özelliğini uygulayabilmemiz için aşağıdaki adımları uygulayacağız.</p><ol><li><strong>CollectionView</strong>’de <strong>dragDelegate</strong> ve <strong>dropDelegate</strong> tanımlarımıza tanımlama yapacağız.</li><li><strong>UICollectionViewDragDelegate</strong>’i uygulayacağız.</li><li><strong>UICollectionViewDropDelegate</strong>’i uygulayacağız.</li><li><strong>ReOrder</strong> fonksiyonumuzda <strong>snapshot</strong> güncelleyeceğiz.</li></ol><p>O zaman haydi başlayalım.</p><ol><li><strong>CollectionView’de dragDelegate ve dropDelegate </strong>tanımlaması</li></ol><p><strong>Sürükle &amp; Bırak</strong> özelliğini kullanabilmek için <strong>collectionView</strong>’de bu delegateleri tanımlamak gereklidir. Aşağıdaki kod örneğinde olduğu gibi tanımlayıp ek olarak <strong>dragInteractionEnabled </strong>özelliğini<strong> </strong>de <strong>true</strong> yapalım.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5558614767e89de0170702d27febc3b/href">https://medium.com/media/a5558614767e89de0170702d27febc3b/href</a></iframe><p>2. <strong>UICollectionViewDragDelegate</strong>’i uygulayalım.</p><p>DragDelegate’i dinlenerek <strong>itemsForBeginning </strong>fonksiyonu ile sürüklenmek istenen nesne dönülür.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7027a7c5350512c7c16c5aa9a1f96a08/href">https://medium.com/media/7027a7c5350512c7c16c5aa9a1f96a08/href</a></iframe><blockquote><strong>NSItemProvider</strong> içerisindeki obje <strong>her zaman uniq</strong> olan bir değer olmalıdır! Yoksa sürükle bırak yaparken kaydırma sırasında uygulamada hata ile karşılaşırsınız!</blockquote><p>3. <strong>UICollectionViewDropDelegate</strong>’i uygulayalım.</p><p>DropDelegate’in aşağıdaki 2 fonksiyonunu kullanacağız. Bunlar;</p><ul><li><strong>dropSessionDidUpdate</strong></li><li><strong>performDropWith</strong></li></ul><p>3.a. <strong>dropSessionDidUpdate</strong></p><p>Cell sürükle yapıp diğer celleri kaydırırken bu metot üzerinden <strong>cellerin hareket yapabilme bilgisini alır</strong>. Eğer <strong>operation: forbidden</strong> olursa cell bulunduğu konumdan başka noktaya hareket edemez.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/549e3d89d0ee0ae3f35c5e009c789b70/href">https://medium.com/media/549e3d89d0ee0ae3f35c5e009c789b70/href</a></iframe><p>Belirli indexte bulunan cell objelerinin hareket etmemesini isterseniz de <strong>destinationIndexPath?.row </strong>kontrolü ile hareketi kısıtlayabilirsiniz.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/272/1*1UkoI_VCFq7jKCB5OFkJvg.png" /><figcaption>row[0] hareketi kısıtlanırsa bu şekilde görünür</figcaption></figure><p>3.b. <strong>performDropWith</strong></p><p>Bırak işleminin <strong>collectionView de uygulanmasını sağlar</strong>. Coordinator’de <strong>Sürükle yapılan item</strong> ve <strong>Bırak yapılan hedef noktası bilgisi</strong> bulunur.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb55e23d13c7a5bccadd901d68f86ab5/href">https://medium.com/media/bb55e23d13c7a5bccadd901d68f86ab5/href</a></iframe><p>4. <strong>ReOrder</strong> fonksiyonumuzda <strong>snapshot</strong> güncelleyelim</p><p>İstediğimiz cell objesini listede istediğimiz noktaya sürükleyip bıraktık. Bıraktığımız anda <strong>reOrderItems </strong>fonksiyonu ile <strong>dataSource</strong> içerisindeki <strong>snapshotta moveItem </strong>yaparak listede objelerin yerlerini değiştiriyoruz.</p><p>Düzenlenmiş <strong>snapshot bilgisini de dataSource’da apply</strong> yaptığımız anda artık collectionView içerisinde nesnelerimiz istediğimiz noktalarda olacak şekilde listemiz kendisini yeniliyor ve <strong>Sürükle &amp; Bırak yapılmış oluyor</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d604dbb232ed2b2f8ca160cc6a39b331/href">https://medium.com/media/d604dbb232ed2b2f8ca160cc6a39b331/href</a></iframe><p><strong>Peki değişen listenin en güncel haline nasıl ulaşırım?</strong></p><p>Cevap aslında çok basit. DataSource <strong>snapshot</strong> içerisindeki <strong>itemIdentifiers</strong> fonksiyonu ile <strong>listenin güncel halini</strong> elde edebilirsiniz.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33fd52346197e130a448a85cdeecd8b3/href">https://medium.com/media/33fd52346197e130a448a85cdeecd8b3/href</a></iframe><p>Yukarıdaki gibi <strong>outputDelegate</strong> ile Sürükle &amp; Bırak işleminin bittiğinin bilgisini aldığımızda <strong>listenin son haline</strong> ulaşıp farklı farklı işlemler de yaptırtabilirsiniz.</p><p><strong>Sonuç</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/296/1*OLXB2R0gARLqvyHf7I0qVA.gif" /></figure><blockquote>DiffableDataSource’un <strong>avantaj</strong>larından birisi de <strong>listede sadece snapshot içerisinde güncellenen veriler yenilendiği</strong> için <strong>Sürükle &amp; Bırak</strong> işleminde DiffableCollectionView kullanılması <strong>daha kullanışlı ve verimli</strong> olduğunu düşünmekteyim.</blockquote><p>Projenin kaynak kodlarını aşağıdaki bağlantıdan inceleyebilirsiniz.</p><p><a href="https://github.com/burakekmen/DraggableDiffableCollectionView">GitHub - burakekmen/DraggableDiffableCollectionView: DragDelegate, DropDelegate sample with DiffableCollectionView</a></p><p>Yararlanılan Kaynaklar:</p><ul><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewdragdelegate">Apple Developer Documentation</a></li><li><a href="https://developer.apple.com/documentation/uikit/uicollectionviewdropdelegate">Apple Developer Documentation</a></li><li><a href="https://medium.com/hackernoon/how-to-drag-drop-uicollectionview-cells-by-utilizing-dropdelegate-and-dragdelegate-6e3512327202">How to Drag &amp; Drop UICollectionView Cells by utilizing DropDelegate and DragDelegate</a></li><li><a href="https://stackoverflow.com/a/60674241">UICollectionViewDropDelegate and DiffableDataSource</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=34bfc26f0e4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>