<?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 Abhishek Suryavanashi on Medium]]></title>
        <description><![CDATA[Stories by Abhishek Suryavanashi on Medium]]></description>
        <link>https://medium.com/@iosdev.abhi?source=rss-db54260bba8------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FKB0e_CSu4RW9q3RUZYtJg.jpeg</url>
            <title>Stories by Abhishek Suryavanashi on Medium</title>
            <link>https://medium.com/@iosdev.abhi?source=rss-db54260bba8------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:34:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@iosdev.abhi/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[I Got Tired of Rewriting iOS Networking Layers. So I Open-Sourced the Fix.]]></title>
            <link>https://medium.com/@iosdev.abhi/i-got-tired-of-rewriting-ios-networking-layers-so-i-open-sourced-the-fix-5a9c3292b76b?source=rss-db54260bba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a9c3292b76b</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swift-package-manager]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Abhishek Suryavanashi]]></dc:creator>
            <pubDate>Tue, 30 Jun 2026 05:15:31 GMT</pubDate>
            <atom:updated>2026-06-30T05:15:31.493Z</atom:updated>
            <content:encoded><![CDATA[<p>A Swift macro that turns a JSON sample into a complete, typed iOS API client — auth, retry, caching, pagination, and observability built in.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-_VF1L4SOR6A017BvLE_w.png" /></figure><p>Every iOS app I’ve shipped started the same way.</p><p>Hand-write the Codable models. Map the snake_case keys. Wire up a retry policy. Add token refresh. Build a cache. Write a pagination state machine. Bolt on some analytics hooks.</p><p>Different code in every company. Slightly buggy in every company. Shared by no one — because that “networking layer” is always welded to that app’s models, that app’s auth, that app’s design system.</p><p>After enough times, I stopped seeing it as work and started seeing it as waste. So I built it once, properly, and open-sourced it.</p><p>It’s called SmartAPI, it’s MIT-licensed, and the whole thing — typed model, observable loader, paginated SwiftUI list — fits in one macro call:</p><pre>@SmartAPI(sample: &quot;&quot;&quot;<br>{ &quot;items&quot;: [{&quot;id&quot;: 1, &quot;title&quot;: &quot;Hello&quot;}], &quot;total_count&quot;: 1247 }<br>&quot;&quot;&quot;, paginated: .page(items: &quot;items&quot;, total: &quot;total_count&quot;))<br>enum Posts {}</pre><p>That’s it. You now have:</p><p>- Posts.Model — a typed Codable + Sendable + Hashable + Identifiable struct</p><p>- Posts.loader(url:) — an @Observable paginated loader with retry, cache, auth, dedup</p><p>- SmartPaginatedView(loader:) — a SwiftUI infinite-scroll list with pull-to-refresh</p><p>Drop it into a view:</p><pre>SmartPaginatedView(loader: Posts.loader(url: postsURL, fetcher: client)) { post in<br>    PostRowView(post: post)   // your view, your design system<br>}</pre><p>No Codable written by hand. No CodingKeys. No init(from:). No retry loops, no URLSession plumbing, no pagination state machine.</p><h3>Four steps. That’s the whole API.</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oop9P9JZlKTErRfsTnZ6gw.png" /><figcaption>Quick start</figcaption></figure><ol><li>Add the package.</li><li>Paste a real API response into @SmartAPI(sample:).</li><li>Create a loader, call load().</li><li>Bind it to a SwiftUI view.</li></ol><p>You get a typed, networked, cached screen. Let me show you what’s actually happening underneath.</p><h3>How the JSON becomes typed Swift</h3><p>The macro runs at compile time. It reads your sample and infers the Swift types from the shape of the data:</p><pre>@SmartAPI(sample: &quot;&quot;&quot;<br>{<br>  &quot;id&quot;: 42,<br>  &quot;name&quot;: &quot;Ada Lovelace&quot;,<br>  &quot;avatar_url&quot;: &quot;https://example.com/ada.jpg&quot;,<br>  &quot;is_active&quot;: true,<br>  &quot;created_at&quot;: &quot;2024-01-15T10:30:00Z&quot;,<br>  &quot;tags&quot;: [&quot;math&quot;, &quot;computing&quot;]<br>}<br>&quot;&quot;&quot;, scope: .parseOnly)<br>enum User {}</pre><p>What gets generated:</p><ul><li>id: 42 becomes let id: Int (and Identifiable)</li><li>avatar_url becomes let avatarURL: URL (key ends in _url)</li><li>is_active becomes let isActive: Bool (snake_case to camelCase)</li><li>created_at becomes let createdAt: Date (ISO-8601 detected)</li><li>tags becomes let tags: [String]</li></ul><p>Plus CodingKeys, the conformances, and a public init. You wrote a JSON sample; the macro wrote about 200 lines of typed Swift.</p><p>If you have an OpenAPI spec, a CLI does this for every schema at once:</p><pre>swift run smartapi-bundle openapi stripe-spec.json Sources/Generated/<br># 203 schemas imported</pre><h3>“But if I have to paste JSON, why not just use Alamofire?”</h3><p>This is the first question everyone asks, so let me answer it head-on — because the answer flips it into a strength.</p><p>You need the JSON shape with any tool. You cannot write this without knowing the response:</p><pre>struct User: Codable {<br>    let id: Int<br>    let name: String<br>    let avatarURL: URL<br>    // ...how did you know these fields and types? You looked at the JSON.<br>}</pre><p>The JSON sample isn’t unique to SmartAPI — it’s a precondition for integrating any API with any library. The only difference is who turns it into Swift:</p><ul><li>With Alamofire: you read the JSON, then hand-write the struct, the CodingKeys, the decoder, the retry, the pagination, the cache — and maintain all of it as the API changes.</li><li>With SmartAPI: you paste the same JSON once, and the macro generates all of it.</li></ul><p>Pasting the sample replaces the transcription work — it doesn’t add to it. And if you don’t have a sample, you curl the endpoint once (you’d do that anyway), or you point the CLI at an OpenAPI spec and paste nothing at all.</p><p>It’s also more resilient than hand-written models, not less: strict: false makes missing or wrong-typed fields fall back to defaults instead of crashing, and schema-drift detection warns you when the live API diverges from your sample — something a hand-rolled Codable never tells you.</p><h3>The macro isn’t the interesting part. The runtime is.</h3><p>Code generation is fine — other tools generate models from JSON. What I really wanted was the production runtime underneath, the stuff every real app needs and every team reimplements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PWCyRMiDOGOFMGNBmXr4Qg.png" /><figcaption>Pipeline</figcaption></figure><p>Auth with refresh — and concurrent-refresh dedup.</p><pre>let provider = BearerTokenProvider(initialToken: token) { try await refresh() }<br>let client = SmartClient(authorization: provider, retryPolicy: .standard)</pre><p>If two requests both hit a 401 at once, only one refresh handler runs. Some identity providers revoke refresh tokens on reuse — concurrent refreshes can lock your user out. This is the kind of bug that only appears under load, in production, on someone else’s device.</p><p>A retry policy that won’t double-POST.</p><pre>.standard            // retries 5xx + timeouts; refuses POST/PATCH by default<br>.allowsUnsafeRetries // opt-in, for endpoints with idempotency keys<br>.none                // never — for audit logs, legal writes</pre><p>A request times out on the wire. The client retries. But it had already reached the server. You just charged the customer twice. .standard refuses to auto-retry non-idempotent methods unless you explicitly opt in.</p><p>Offline cache, request dedup, observability.</p><pre>@SmartAPI(sample: &quot;...&quot;, cache: true)<br>enum User {}</pre><p>The loader reads cache, shows it instantly, then refreshes in the background. If the refresh fails, the screen keeps the cached data and shows a stale banner instead of going blank. Two screens mounting the same loader share one network request. And every retry, refresh, cache miss, and decode fallback flows through one observer protocol you can wire to your analytics.</p><p>Pagination — three strategies, one line of SwiftUI.</p><pre>.cursor(items: &quot;data&quot;, nextCursor: &quot;next_cursor&quot;, hasMore: &quot;has_more&quot;)  // Stripe / Slack<br>.page(items: &quot;items&quot;, total: &quot;total_count&quot;, pageSize: 30)               // GitHub / Rails<br>.offset(items: &quot;results&quot;, total: &quot;total&quot;, pageSize: 25)                 // Algolia</pre><p>All three behave identically for the caller — loader.items, loader.hasMore, loader.loadMore() — with infinite scroll and pull-to-refresh handled by SmartPaginatedView.</p><h3>When you should NOT use this</h3><p>Here’s the honest part — and telling you when not to use my library is the most credible thing I can do as a maintainer who shipped this days ago.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sa9JXGl_pahsmL0g-i8Fag.png" /><figcaption>Decision</figcaption></figure><ul><li>Mission-critical app shipping next month? Use a battle-tested client. SmartAPI is v0.1.0, one maintainer. Alamofire has a decade of hardening and millions of apps. No feature list beats that for a high-stakes launch.</li><li>Need deep low-level control? (cert pinning, custom TLS, multipart streaming, request interceptors) Stay low-level.</li></ul><p>Use SmartAPI when you’re starting a new project, building an internal tool or prototype, or you’re just tired of rebuilding the same model + retry + cache + pagination layer on every app.</p><p>SmartAPI isn’t competing with Alamofire — it sits above it and uses URLSession under the hood. They give you a great HTTP client; SmartAPI generates everything you’d hand-write on top.</p><h3>Try it</h3><pre>// Package.swift<br>.package(url: &quot;https://github.com/AbhishekSuryawanshi/SmartAPI.git&quot;, from: &quot;0.1.1&quot;)</pre><p>Requires Swift 6.0+, Xcode 16+, iOS 17+, macOS 14+.</p><pre>import SmartAPI<br>@SmartAPI(sample: realJSONFromYourAPI, scope: .parseOnly)<br>enum User {}<br>let loader = User.Loader(url: yourEndpointURL)<br>await loader.load()<br>print(loader.state.value)  // typed User.Model</pre><p>The repo: <a href="http://github.com/AbhishekSuryawanshi/SmartAPI">github.com/AbhishekSuryawanshi/SmartAPI</a></p><p>It’s built under Swift 6 strict mode, ExistentialAny, and warnings-as-errors, clean. 78 tests — 17 of them URLProtocol-based integration tests that exercise the real retry, auth, and coalescer paths against an actual URLSession, not just unit tests of internal predicates.</p><p>If you try it: star the repo, file issues on the rough edges, and tell me what’s missing for your codebase. I’d genuinely rather have one team adopt it on a real project than collect a hundred stars from drive-by readers.</p><p>And if you’re starting a new iOS app this week — try not writing the networking layer this time. I already wrote it.</p><p>The repo is at <a href="http://github.com/AbhishekSuryawanshi/SmartAPI">github.com/AbhishekSuryawanshi/SmartAPI</a>. If this saved you some boilerplate, a star helps it reach other people stuck rewriting the same layer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a9c3292b76b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an Audio & Video App with WebRTC on iOS: One Codebase, Four Signaling Options, Zero…]]></title>
            <link>https://medium.com/@iosdev.abhi/building-an-audio-video-app-with-webrtc-on-ios-one-codebase-four-signaling-options-zero-8b22a5cbe6e6?source=rss-db54260bba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b22a5cbe6e6</guid>
            <category><![CDATA[webrtc]]></category>
            <category><![CDATA[audio-call]]></category>
            <category><![CDATA[signaling]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[video-call]]></category>
            <dc:creator><![CDATA[Abhishek Suryavanashi]]></dc:creator>
            <pubDate>Sun, 08 Feb 2026 16:33:17 GMT</pubDate>
            <atom:updated>2026-02-08T16:33:17.106Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building an Audio &amp; Video App with WebRTC on iOS: One Codebase, Four Signaling Options, Zero Backend</h3><p>If you’ve ever tried to build a peer-to-peer video call on iOS using native WebRTC, you know the pain. The official documentation is sparse. Most tutorials lean on JavaScript bridges or outdated Objective-C examples. The handful of Swift samples that do exist stop at “here’s how to create an offer” and leave you stranded when it comes to the hardest part — signaling.</p><p>This article walks through <strong>WebRTCDemo</strong>, an open-source iOS app that implements real, working video calls using Google’s WebRTC framework — and does it four completely different ways, without a single backend server. Each strategy teaches you something different about how WebRTC actually works under the hood.</p><p>The app ships four signaling modes:</p><ol><li><strong>Quick Test</strong> bundles everything into a single copy-paste blob for the fastest possible test.</li><li><strong>Learn</strong> breaks the protocol apart step by step so you can see SDP and ICE in isolation.</li><li><strong>Multipeer</strong> uses Apple’s MultipeerConnectivity for automatic Bluetooth/WiFi exchange.</li><li><strong>Local Network</strong> uses Network.framework with Bonjour for TCP-based signaling over WiFi.</li></ol><p>All four end up at the same place — a full-screen video call with a draggable picture-in-picture local preview, speaker/mute/camera controls, and call duration tracking.</p><p>The full source is available on GitHub: <a href="https://github.com/AbhishekSuryawanshi/WebRTCDemo.git">https://github.com/AbhishekSuryawanshi/WebRTCDemo.git</a></p><p>Let’s break it down.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FOg_Pffgi5bht0awjhj93w.png" /></figure><h4>Architecture Overview</h4><p>The project follows <strong>MVVM + Services</strong>, a pattern that maps cleanly to SwiftUI’s state-driven rendering while keeping WebRTC’s complexity behind clean abstractions.</p><p>WebRTCDemo/<br>├── Core/<br>│ ├── WebRTCClient.swift<br>│ ├── WebRTCConfig.swift<br>│ ├── WebRTCTrackManager.swift<br>│ └── WebRTCClientDelegate.swift<br>├── Services/<br>│ ├── MultipeerService.swift<br>│ └── LocalNetworkService.swift<br>├── ViewModels/<br>│ └── CallViewModel.swift<br>├── Views/<br>│ ├── CallView.swift<br>│ ├── VideoRendererView.swift<br>│ └── …<br>├── Models/<br>│ ├── SignalingMessage.swift<br>│ ├── SignalingBundle.swift<br>│ ├── SessionDescription.swift<br>│ ├── IceCandidate.swift<br>│ └── CallState.swift<br>└── Utilities/<br> └── RTCPeerConnection+Async.swift</p><h4>Key design decisions:</h4><p><strong>@MainActor</strong> on all ViewModels and Services — SwiftUI requires published properties to update on the main thread. Rather than sprinkling <em>DispatchQueue.main.async</em> everywhere, we annotate the entire class.</p><p><strong>nonisolated delegates </strong>— WebRTC’s C++ core calls delegates on arbitrary threads. Each delegate method is marked <em>nonisolated</em> and dispatches back via <em>Task { @MainActor in }</em>.</p><p><strong>Swift actor</strong> for <em>WebRTCTrackManager</em> — camera capture is inherently stateful and must be serialized. An actor eliminates race conditions with zero boilerplate.</p><p><strong>Combine publishers</strong> for reactive state observation — <em>CallViewModel </em>subscribes to <em>WebRTCClient.$iceConnectionState</em> and friends to drive state transitions and UI updates.</p><ul><li>Models: Encodable SDP and ICE so they can be sent as JSON (clipboard, Multipeer, or TCP).</li><li>Core: WebRTCClient owns the peer connection, offer/answer, ICE, and media; WebRTCTrackManager (actor) handles camera/mic and tracks.</li><li>View model: Decides <em>how</em> to exchange signaling (manual vs automatic) and drives the UI state.</li><li>Views: Mode selection, call UI, and signaling sheet (tabs for SDP/ICE in Learn mode, steps for Quick Test, peer lists for Multipeer/Local Network).</li></ul><h3>1. WebRTC Core: One Client to Rule Them All</h3><p>Regardless of signaling method, the same WebRTC client is used.Initialize once (e.g. when starting a call):</p><ul><li>Configure audio session before creating the WebRTC factory (so WebRTC doesn’t override your route).</li><li>Create RTCPeerConnectionFactory, then RTCPeerConnection with your ICE config.</li><li>Create and add local audio/video tracks, start camera capture.</li></ul><p><strong>Offer/answer flow:</strong></p><ul><li>Caller: createOffer() → set local description → send the resulting SDP (and later ICE) to the peer.</li><li>Callee: receive remote offer → setRemoteDescription(offer) → createAnswer() → set local description → send answer (and ICE) back.</li></ul><p><strong>ICE candidates:</strong></p><ul><li>WebRTC gathers candidates asynchronously. If the remote description isn’t set yet, buffer incoming candidates and apply them after setRemoteDescription. That way order doesn’t matter.</li></ul><p>Example: wrapping WebRTC’s callback-based API with async/await so the rest of the app can use async flows:</p><pre>// RTCPeerConnection+Async.swift<br>extension RTCPeerConnection {<br>    func offer(for constraints: RTCMediaConstraints) async throws -&gt; RTCSessionDescription {<br>        try await withCheckedThrowingContinuation { continuation in<br>            self.offer(for: constraints) { sdp, error in<br>                if let error = error { continuation.resume(throwing: error) }<br>                else if let sdp = sdp { continuation.resume(returning: sdp) }<br>                else { continuation.resume(throwing: CallError.localDescriptionFailed) }<br>            }<br>        }<br>    }<br>    // same idea for answer(), setLocalDescription(), setRemoteDescription()<br>}</pre><p>Your client then uses these async methods and exposes a simple API: createOffer(), createAnswer(), setRemoteDescription(_:), addRemoteCandidate(_:) / addRemoteCandidates(_:).</p><h3>2. Codable Signaling: SDP and ICE as JSON</h3><p>Signaling is “whatever channel you use to exchange SDP and ICE.” To support copy-paste, Multipeer, and TCP, we make those objects Codable and wrap them in a single message type.Session description (offer/answer):</p><pre>struct SessionDescription: Codable, Equatable {<br>    let type: SDPType  // .offer / .answer<br>    let sdp: String<br>    // init(from rtcSessionDescription: RTCSessionDescription)<br>    // var rtcSessionDescription: RTCSessionDescription<br>}</pre><p>ICE candidate:</p><pre>struct IceCandidate: Codable, Equatable, Identifiable {<br>    let id: UUID<br>    let sdp: String<br>    let sdpMLineIndex: Int32<br>    let sdpMid: String?<br>    // init(from rtcIceCandidate: RTCIceCandidate)<br>    // var rtcIceCandidate: RTCIceCandidate<br>}</pre><p>One message type for all signaling:</p><pre>enum SignalingMessage: Codable {<br>    case sdp(SessionDescription)<br>    case candidate(IceCandidate)<br>    case candidates([IceCandidate])<br>    case bundle(SignalingBundle)  // SDP + candidates in one blob<br>}<br>struct SignalingBundle: Codable {<br>    let sdp: SessionDescription<br>    let candidates: [IceCandidate]<br>}</pre><p>Then:</p><ul><li>Manual (Learn): Send/paste .sdp and .candidates as JSON.</li><li>Quick Test: Build a SignalingBundle, encode as .bundle, copy-paste once per device.</li><li>Multipeer / Local Network: Encode SignalingMessage.bundle(bundle) and send over the transport; decode on the other side and apply SDP + candidates.</li></ul><h3>3. The Four Signaling Modes in Practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mC_Pngrzf3-tWrhGxQR_Hw.png" /><figcaption>Mode selection screen showing all 4 mode cards</figcaption></figure><h3>Quick Test — One bundle per device</h3><ul><li>Caller: create offer → wait for ICE gathering (or a short timeout) → build SignalingBundle(sdp: localDescription, candidates: localCandidates) → show JSON; user copies/shares.</li><li>Callee: create answer after receiving offer → same bundle building → user copies/shares.</li><li>On each device, user pastes the other side’s bundle JSON. App decodes SignalingMessage.bundle, then:</li><li>setRemoteDescription(bundle.sdp)</li><li>If callee and bundle is an offer: createAnswer()</li><li>addRemoteCandidates(bundle.candidates)</li></ul><p>So the “signaling channel” is the user (clipboard, AirDrop, etc.); the app only needs to produce and consume one JSON blob per peer.</p><h3>Learn — Step-by-step SDP and ICE</h3><ul><li>Same WebRTC flow, but the UI separates:</li><li>SDP tab: Copy my offer/answer; paste peer’s SDP → apply → if callee and it’s an offer, create answer.</li><li>ICE tab: Copy my candidates (as .candidates JSON); paste peer’s candidates → apply.</li><li>No bundling; each step is visible. Great for understanding the order: offer → answer → ICE both ways.</li></ul><h3>Multipeer — Automatic over Bluetooth / WiFi</h3><ul><li>Use MultipeerConnectivity: both devices advertise and browse the same service type (e.g. “webrtc-demo”).</li><li>When the user selects a discovered peer, invite to an MCSession. Once connected, you have a byte stream.</li><li>Caller: when the session is connected and the local bundle (SDP + candidates) is ready, encode SignalingMessage.bundle(bundle) and send with session.send(_:toPeers:with:).</li><li>Callee: on session(_:didReceive:fromPeer:), decode the message, apply the bundle (set remote description, create answer, add candidates), then build <em>their</em> bundle and send it back the same way.</li><li>No copy-paste; discovery and exchange are in-app.</li></ul><h3>Local Network — Automatic over same WiFi</h3><ul><li>One device hosts (advertise via Bonjour, e.g. _webrtclocal._tcp, and listen with NWListener).</li><li>Other device browses (e.g. NWBrowser for that type), then connects to the chosen NWBrowser.Result with NWConnection(to:using:).</li><li>Run the listener and connection on a dedicated queue so Network.framework doesn’t block the main thread.</li><li>Framing: TCP is a stream. Send a 4-byte big-endian length prefix, then the JSON payload; on receive, read 4 bytes, then read that many bytes and decode SignalingMessage.bundle.</li><li>Same “bundle exchange” logic as Multipeer: caller sends bundle when ready; callee applies it, creates answer, gathers ICE, sends their bundle back.</li></ul><p>So you get four options with one WebRTC flow and one signaling <em>format</em> (SDP + ICE in JSON), and only the <em>transport</em> (clipboard vs Multipeer vs TCP) changes.</p><h3>4. Media: Tracks and Camera</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QqdTcZt0q1XO7fIxiilsFQ.png" /></figure><p>Audio:Use a single audio source/track from the factory with optional echo cancellation and noise suppression. Add it to the peer connection. Route (e.g. speaker vs earpiece) is controlled via AVAudioSession; set category (e.g. .playAndRecord), mode (e.g. .videoChat), and override output as needed. WebRTC’s manual audio session mode helps so that your app’s route choices aren’t overwritten when the audio unit starts.Video:Use an actor for anything that touches the camera so all access is serialized:</p><ul><li>Create RTCVideoSource and RTCCameraVideoCapturer, then a video track from the factory.</li><li>In the actor, resolve the front/back camera, pick a format (e.g. 640×480) and FPS, then call capturer.startCapture(with:format:fps:completion:). Wrap the completion handler in withCheckedThrowingContinuation so you can await from the ViewModel.</li><li>Mute/video off = set track.isEnabled = false; camera flip = stop capture, switch device, start again.</li></ul><p>Rendering: use RTCMTLVideoView (or equivalent) and add/remove the view to/from the RTCVideoTrack when the track changes; wrap in UIViewRepresentable for SwiftUI.</p><h3>5. State and UX</h3><p>Call state machine:Model the call with an enum, e.g. idle → initiating → connecting → connected (and reconnecting, ending, ended, failed). Enforce valid transitions (e.g. canTransition(to:)) so you never end up in an invalid combination. Drive transitions from:</p><ul><li>User actions (start call, end call).</li><li>ICE connection state (e.g. .connected / .completed → connected; .failed → failed; .disconnected → reconnecting).</li></ul><p>UI:</p><ul><li>Show connection state (e.g. “Connecting…”, “Connected”) and ICE gathering progress so users know what’s happening.</li><li>In automatic modes, show “Discovering…” → “Connecting…” → “Exchanging…” → “Connected” so the flow is clear.</li><li>For manual modes, disable “Apply” until there’s something to apply and show short success/error messages after apply/copy.</li></ul><h3>6. Permissions and Entry Point</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Z4tnlqLAGfeE8NEK_djCw.png" /></figure><ul><li>Request camera and microphone before creating the WebRTC factory or tracks. Use a single PermissionManager (e.g. ObservableObject) that checks and requests both, and only then show the main UI (e.g. HomeView).</li><li>If the user has denied, show a screen that explains why permissions are needed and offers a button to open Settings (UIApplication.openSettingsURLString).</li></ul><h3>7. What You Can Reuse in Your Own App</h3><ul><li>One WebRTC client with async offer/answer/setRemote/addRemoteCandidates and ICE buffering until remote description is set.</li><li>Codable SDP and ICE plus a single SignalingMessage (and SignalingBundle) so the same format works for manual and automatic transport.</li><li>Four signaling “transports”: clipboard (Quick Test + Learn), Multipeer, Local Network. Swap or add another (e.g. WebSocket) without changing the WebRTC or bundle-apply logic.</li><li>Actor-based track manager for camera and optional resolution/FPS presets.</li><li>Explicit audio session configuration and manual WebRTC audio so speaker/earpiece behavior stays under your control.</li><li>Call state machine and clear UI states so users always know where they are in the flow.</li></ul><h3>Summary</h3><p>You can build one iOS app that does peer-to-peer audio and video with WebRTC and supports multiple signaling options: quick one-paste bundles, step-by-step learning, Multipeer, and Local Network. The same core (client, SDP/ICE handling, tracks, and state machine) stays the same; only the way you <em>deliver</em> the signaling data changes. That makes the app a good base for learning, demos, or evolving toward a production design (e.g. replacing one transport with your own signaling server).If you want, the next post can go deeper into one of: STUN/TURN configuration, reconnection and ICE restart, or adding a WebSocket signaling path to the same codebase.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b22a5cbe6e6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Add Game Center Leaderboards to Your iOS Game: A Step-by-Step Guide]]></title>
            <link>https://medium.com/@iosdev.abhi/add-game-center-leaderboards-to-your-ios-game-a-step-by-step-guide-a2222ab7d3fb?source=rss-db54260bba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2222ab7d3fb</guid>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[gamecenter]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[leaderboard]]></category>
            <dc:creator><![CDATA[Abhishek Suryavanashi]]></dc:creator>
            <pubDate>Wed, 30 Oct 2024 17:04:39 GMT</pubDate>
            <atom:updated>2024-10-30T17:06:25.745Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>Integrating Game Center in your iOS game can significantly enhance user engagement by allowing players to compare their scores on global leaderboards. In this tutorial, I’ll guide you through creating a Game Center Leaderboard using Swift, including authenticating users, submitting scores, fetching the best score, and displaying the leaderboard.</em></strong></p><h3><strong>Prerequisites</strong></h3><p>Before diving in, make sure you have:</p><p>1. An iOS project set up in Xcode.</p><p>2. Game Center enabled for your app in <strong>App Store Connect</strong>.</p><p>3. A Game Center Leaderboard created in your app’s App Store Connect configuration.</p><h3>Let’s get started!</h3><p><strong>Step 1: Setting Up Game Center in Your Project</strong></p><p>To enable Game Center:</p><ol><li>Go to <strong>App Store Connect</strong> &gt; <strong>My Apps</strong> &gt; <strong>Your App</strong> &gt; <strong>Growth &amp; Marketing</strong> &gt; <strong>Game Center</strong>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*N3WGr-yZGxA1M9WH5ulY7Q.png" /></figure><p>2. Enable Game Center and create a new leaderboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V3T5zMJvteE2M_IAgKjEOQ.png" /></figure><p>3. Note the <strong>Leaderboard ID</strong>, as we’ll use it in the code.</p><p>Next, import GameKit in your project</p><p><strong>Step 2: Setting Up the Game Center Helper Class</strong></p><p>We’ll create a helper class, GameCenterHelper, as a singleton to manage all interactions with Game Center. This modular approach keeps the code organized and easy to update.</p><pre>import GameKit<br><br>class GameCenterHelper: NSObject, GKGameCenterControllerDelegate {<br>    static let shared = GameCenterHelper()<br>    private let leaderboardID = &quot;your_leaderboard_id_here&quot; // Replace with your actual Leaderboard ID<br>    private let userDefaults: UserDefaults<br>    private let application: UIApplication<br>    <br>    init(userDefaults: UserDefaults = .standard, application: UIApplication = .shared) {<br>        self.userDefaults = userDefaults<br>        self.application = application<br>    }<br>}</pre><p><strong>Note:</strong> Replace “your_leaderboard_id_here” with your <strong>Leaderboard ID</strong> created in App Store Connect.</p><p><strong>Step 3: Authenticating the Player</strong></p><p>To use Game Center, users must be authenticated. Here’s the authenticateUser function, which checks the player’s login status and presents a login view if they aren’t logged in.</p><p>Add the authenticateUser function to GameCenterHelper:</p><pre>func authenticateUser() {<br>    let player = GKLocalPlayer.local<br>    player.authenticateHandler = { viewController, error in<br>        if let vc = viewController {<br>            self.presentGameCenterViewController(viewController: vc)<br>        } else if player.isAuthenticated {<br>            print(&quot;Player authenticated&quot;)<br>            self.fetchBestScoreFromLeaderboard { bestScore in<br>                if let bestScore = bestScore {<br>                    self.userDefaults.set(bestScore, forKey: &quot;bestScore&quot;)<br>                    GameManager.shared.updateBestScore(bestScore)<br>                }<br>            }<br>        } else {<br>            self.handleError(error, context: &quot;Authenticating Player&quot;)<br>        }<br>    }<br>}</pre><p>This function authenticates the player and, if successful, fetches their best score from the leaderboard.</p><p><strong>Step 4: Displaying the Leaderboard</strong></p><p>Once the player is authenticated, they can view the leaderboard by calling showLeaderboard. Here’s the code for this function:</p><pre>func showLeaderboard(completion: (() -&gt; Void)? = nil) {<br>    performAuthenticatedAction {<br>        let gcViewController = GKGameCenterViewController(leaderboardID: self.leaderboardID, playerScope: .global, timeScope: .allTime)<br>        gcViewController.gameCenterDelegate = self<br>        <br>        if let scene = self.application.connectedScenes.first as? UIWindowScene {<br>            scene.keyWindow?.rootViewController?.present(gcViewController, animated: true, completion: completion)<br>        }<br>    }<br>}</pre><p>The showLeaderboard method opens a GKGameCenterViewController to display the leaderboard associated with the specified leaderboardID.</p><p><strong>Step 5: Submitting Scores to the Leaderboard</strong></p><p>To keep users’ scores up-to-date, we’ll implement submitScoreToLeaderboard, which submits the latest score to Game Center:</p><pre>func submitScoreToLeaderboard(score: Int) {<br>    performAuthenticatedAction {<br>        GKLeaderboard.submitScore(score, context: 0, player: GKLocalPlayer.local, leaderboardIDs: [self.leaderboardID]) { error in<br>            self.handleError(error, context: &quot;Submitting Score&quot;)<br>        }<br>    }<br>}</pre><p>This method calls submitScoreToLeaderboard(score:) with the player’s score, making it accessible on the leaderboard.</p><p><strong>Step 6: Fetching the Best Score from the Leaderboard</strong></p><p>Fetching the player’s best score from the leaderboard is essential if you want to display it locally in your app. Here’s how:</p><pre>private func fetchBestScoreFromLeaderboard(completion: @escaping (Int?) -&gt; Void) {<br>    performAuthenticatedAction {<br>        GKLeaderboard.loadLeaderboards(IDs: [self.leaderboardID]) { leaderboards, error in<br>            guard let leaderboard = leaderboards?.first, error == nil else {<br>                self.handleError(error, context: &quot;Loading Leaderboard&quot;)<br>                completion(nil)<br>                return<br>            }<br>            <br>            leaderboard.loadEntries(for: [GKLocalPlayer.local], timeScope: .allTime) { localPlayerEntry, _, error in<br>                guard let playerScore = localPlayerEntry, error == nil else {<br>                    self.handleError(error, context: &quot;Loading Player Entry&quot;)<br>                    completion(nil)<br>                    return<br>                }<br>                <br>                let bestScore = Int(playerScore.score)<br>                print(&quot;User&#39;s best score from leaderboard: \(bestScore)&quot;)<br>                completion(bestScore)<br>            }<br>        }<br>    }<br>}</pre><p>This method loads the leaderboard entry for the authenticated player and retrieves their best score, which is then used for any in-game updates.</p><p><strong>Step 7: Modular Error Handling and Logging</strong></p><p>Having a reusable error handler improves code readability and helps with debugging:</p><pre>private func handleError(_ error: Error?, context: String) {<br>    if let error = error {<br>        print(&quot;Error in \(context): \(error.localizedDescription)&quot;)<br>    } else {<br>        print(&quot;Unknown error in \(context).&quot;)<br>    }<br>}</pre><p><strong>Step 8: Reusable Authentication Wrapper</strong></p><p>Since many Game Center actions require authentication, we’ve created a reusable performAuthenticatedAction wrapper. This checks if the player is authenticated and performs the desired action:</p><pre>private func performAuthenticatedAction(_ action: @escaping () -&gt; Void) {<br>    let player = GKLocalPlayer.local<br>    if player.isAuthenticated {<br>        action()<br>    } else {<br>        authenticateUser()<br>    }<br>}</pre><p><strong>Step 9: Presenting Game Center Views</strong></p><p>Finally, presentGameCenterViewController manages the display of Game Center views, dismissing any currently presented view to prevent overlap:</p><pre>private func presentGameCenterViewController(viewController: UIViewController) {<br>    if let scene = application.connectedScenes.first as? UIWindowScene,<br>       let rootViewController = scene.windows.first?.rootViewController {<br>        rootViewController.present(viewController, animated: true, completion: nil)<br>    }<br>}</pre><h3><strong>Wrapping Up</strong></h3><p>With this setup, you now have a modular, flexible, and testable Game Center leaderboard implementation in your iOS game. Here’s a quick recap:</p><p>1. <strong>Authenticate</strong> the player to ensure Game Center functionality.</p><p>2. <strong>Submit</strong> scores and <strong>fetch</strong> the player’s best score to display within the app.</p><p>3. <strong>Display</strong> the leaderboard with a reusable function.</p><p>4. <strong>Handle errors</strong> consistently to improve debugging and user experience.</p><p>This enhanced code structure allows easy updates, error handling, and improved readability, giving you a reliable way to add Game Center leaderboards to your iOS games.</p><p>Happy coding, and may the best scores prevail!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2222ab7d3fb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a 2048 PowerPlay Game for Apple Watch with SwiftUI]]></title>
            <link>https://medium.com/@iosdev.abhi/building-a-2048-powerplay-game-for-apple-watch-with-swiftui-235e71d667c3?source=rss-db54260bba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/235e71d667c3</guid>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[2048-game]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[app-development]]></category>
            <dc:creator><![CDATA[Abhishek Suryavanashi]]></dc:creator>
            <pubDate>Wed, 23 Oct 2024 08:28:46 GMT</pubDate>
            <atom:updated>2024-10-23T08:28:46.621Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/590/1*0B42zCbnhrpXEXgNW4Mi1A.png" /></figure><p>In this post, I’ll walk you through how I built a <strong>2048 PowerPlay game for the Apple Watch</strong> using SwiftUI. This is an extension of my earlier project where I created the game for iPhone and iPad, which I covered in <a href="https://medium.com/@iosdev.abhi/building-2048-powerplay-game-with-swiftui-423bf8a400a9">this Medium post</a>. The challenge this time was adapting the user experience and layout for the smaller, more compact Apple Watch interface while maintaining the same engaging gameplay.</p><p>Let’s dive into the details of the project and how we can leverage SwiftUI to build a fluid, interactive game on watchOS.</p><h3><strong>Overview of the Game</strong></h3><p><strong>For those unfamiliar with the 2048 game, it’s a popular puzzle game where players swipe tiles to combine them. Each swipe adds a new tile (either a 2 or a 4), and the goal is to create a tile with the value 2048 by combining tiles with the same value.</strong></p><p>In this watchOS version of <strong>2048 PowerPlay</strong>, the main elements include:<br> • <strong>Grid View</strong>: A 3x3 grid where tiles slide in different directions based on user swipes.</p><p>• <strong>Score Display</strong>: The current score and best score are updated dynamically as you combine tiles.</p><p>• <strong>Swipe Gestures and Digital Crown</strong>: Users can swipe in four directions to move the tiles or use the digital crown for vertical movement.</p><h4><strong>Key Features of the Watch Version:</strong></h4><p>• <strong>Compact 3x3 Grid</strong>: Unlike the 4x4 grid on iPhone and iPad, the watch uses a smaller 3x3 grid to fit the screen better.</p><p>• <strong>Gesture Control</strong>: The game allows swiping gestures and interaction with the digital crown to move tiles up and down.</p><p>• <strong>Power-ups</strong>: Special tiles such as “Clear Row,” “Clear Column,” and “Double Tile” add more complexity to the game.</p><h3><strong>Game Logic Overview</strong></h3><p>The core of the game is managed by the GameManager, which handles the game’s grid, scores, and moves. Here’s a breakdown of the most important functionality:</p><ol><li><strong>Setting Up the Game<br></strong>The game is initialised by resetting the score, clearing the saved state, and creating a fresh grid:</li></ol><pre>func setupGame() {<br>    currentScore = 0 // Reset score<br>    clearSavedState() // Clear previous saved state<br>    initializeGrid()   // Initialize 3x3 grid<br><br>    // Add two random tiles to start the game<br>    addRandomTile()<br>    addRandomTile()<br>}</pre><p><strong>2. Handling Swipes<br></strong>The game listens for swipe gestures and updates the grid accordingly. The following function detects swipe directions and triggers the appropriate movement:</p><pre>func swipe(direction: Direction) {<br>    switch direction {<br>    case .left: moveLeft()<br>    case .right: moveRight()<br>    case .up: moveUp()<br>    case .down: moveDown()<br>    }<br>    <br>    // Add a new tile after every swipe and save the game state<br>    addRandomTile()<br>    saveGameState()<br>}</pre><p><strong>3. Managing Scores<br></strong>The game keeps track of the current score and the best score. Here’s how scores are updated dynamically:</p><pre>func updateScore(by points: Int) {<br>    DispatchQueue.main.async {<br>        self.currentScore += points<br>        if self.currentScore &gt; self.bestScore {<br>            self.bestScore = self.currentScore // Update best score if needed<br>        }<br>    }<br>}</pre><h4><strong>Building the WatchOS UI</strong></h4><p>For the Apple Watch version, we display the grid using a LazyVGrid and show the scores at the top using a custom ScoreHeaderView. Here’s the key part of the WatchGameView:</p><ol><li><strong>Score Display<br></strong>The score and reset button are placed at the top of the screen:</li></ol><pre>struct ScoreHeaderView: View {<br>    @EnvironmentObject var gameManager: GameManager<br>    <br>    var body: some View {<br>        HStack {<br>            Text(&quot;BEST: \(gameManager.bestScore)&quot;)<br>            Text(&quot;SCORE: \(gameManager.currentScore)&quot;)<br>            Button(action: { gameManager.setupGame() }) {<br>                Image(systemName: &quot;arrow.clockwise&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>2. Grid Layout<br></strong>The 3x3 grid is laid out using a LazyVGrid to ensure the tiles fit dynamically on different screen sizes:</p><pre>GeometryReader { geometry in<br>    let tileSize = min(geometry.size.width / 3, geometry.size.height / 3)<br>    LazyVGrid(columns: Array(repeating: GridItem(.fixed(tileSize)), count: 3)) {<br>        ForEach(0..&lt;9, id: \.self) { index in<br>            let row = index / 3<br>            let col = index % 3<br>            TileView(tile: gameManager.grid[row][col])<br>        }<br>    }<br>}</pre><p><strong>3. Swipe Gesture Handling<br></strong>To make the game interactive, we listen for swipe gestures to move tiles in four directions:</p><pre>.gesture(<br>    DragGesture()<br>        .onEnded { gesture in<br>            let horizontal = gesture.translation.width<br>            let vertical = gesture.translation.height<br>            <br>            if abs(horizontal) &gt; abs(vertical) {<br>                gameManager.swipe(direction: horizontal &gt; 0 ? .right : .left)<br>            } else {<br>                gameManager.swipe(direction: vertical &gt; 0 ? .down : .up)<br>            }<br>        }<br>)</pre><p><strong>4. Digital Crown Integration<br></strong>The Apple Watch version takes advantage of the <strong>Digital Crown</strong> for vertical movements:</p><pre>.digitalCrownRotation($gameManager.crownOffset, from: -1, through: 1, by: 0.1)<br>.onChange(of: gameManager.crownOffset) { value in<br>    gameManager.swipe(direction: value &gt; 0 ? .down : .up)<br>}</pre><h3><strong>Conclusion</strong></h3><p>Adapting <strong>2048 PowerPlay</strong> to the Apple Watch presented new challenges, especially around the UI and input methods. However, with SwiftUI’s declarative framework and watchOS-specific features like the <strong>Digital Crown</strong>, the transition was smooth and enjoyable.</p><p>The game is simple, yet engaging, and leverages gestures and the crown for an immersive experience on a smaller screen.</p><h4><strong>Project Source Code</strong></h4><blockquote>You can find the complete source code for this project on my <a href="https://github.com/AbhishekSuryawanshi/2048PowerPlay_watchGame">GitHub repository</a>.</blockquote><p>If you enjoyed this, check out my previous post on building the <a href="https://medium.com/@iosdev.abhi/building-2048-powerplay-game-with-swiftui-423bf8a400a9">2048 PowerPlay game for iPhone and iPad</a>.</p><h3><strong>Summary:</strong></h3><p>• I have limited the code snippets to key functional parts.</p><p>• The explanation focuses on critical aspects like game setup, swipe handling, grid layout, and score management, avoiding unnecessary full-length code blocks.</p><p>• Readers can find the full code on the GitHub repository.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=235e71d667c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building “2048 - PowerPlay” game with SwiftUI]]></title>
            <link>https://medium.com/@iosdev.abhi/building-2048-powerplay-game-with-swiftui-423bf8a400a9?source=rss-db54260bba8------2</link>
            <guid isPermaLink="false">https://medium.com/p/423bf8a400a9</guid>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[2048]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Abhishek Suryavanashi]]></dc:creator>
            <pubDate>Sat, 19 Oct 2024 19:33:00 GMT</pubDate>
            <atom:updated>2024-10-19T19:33:00.288Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ukqdqDTDAa1vHW1njiCQKg.png" /></figure><h3><strong>Introduction</strong></h3><p>As an iOS developer with over six years of experience, I’ve always enjoyed taking on new challenges, whether it’s building feature-rich apps or exploring unique projects. Recently, I embarked on an exciting journey to recreate the popular 2048 puzzle game with my own twist, called “<strong>2048 PowerPlay”</strong>. What sets this project apart is that I developed it entirely using SwiftUI, Apple’s modern framework for building UIs.</p><p>In this article, I’ll walk you through how I approached this project, the key features I implemented, and how SwiftUI made the development process smoother and more enjoyable. Whether you’re a seasoned developer or just starting out, I hope this insight into my journey with <strong>2048 PowerPlay</strong> will inspire you to create your own projects using SwiftUI.</p><h3><strong>Why SwiftUI?</strong></h3><p>I chose SwiftUI for <strong>2048 PowerPlay</strong> because of its declarative syntax, real-time previews, and built-in animations. SwiftUI allowed me to focus on what the game should do rather than how to implement it, making development smoother. The seamless integration of state management with @State and @Binding simplified handling tile movements and score updates. Plus, SwiftUI’s easy-to-use animations brought the tile merging to life without much effort. In short, SwiftUI was the perfect fit for building an intuitive and dynamic gaming experience.</p><h3><strong>Core Game Features</strong></h3><h4><strong>What’s Different in 2048 PowerPlay?</strong></h4><p><strong>2048 PowerPlay</strong> introduces new elements to the classic 2048 formula:</p><ul><li><strong>Power-Ups</strong>: Along with number tiles, special power-up tiles appear after every few moves. These include:</li><li><strong>Clear Row</strong>: Removes all tiles in the selected row.</li><li><strong>Clear Column</strong>: Removes all tiles in the selected column.</li><li><strong>Double Tile</strong>: Doubles the value of the tile it’s placed on.</li></ul><h4><strong>1. App Entry Point: Setting up the Scene</strong></h4><p>The main entry point of any SwiftUI app is the @main struct. Here’s how the app starts and handles transitioning between the menu and game screens, as well as saving the game state.</p><pre>@main<br>struct _048_PowerPlayApp: App {<br>    @Environment(\.scenePhase) private var scenePhase<br>    @StateObject private var gameManager = GameManager()<br>    @State private var hasSavedGame: Bool = UserDefaults.standard.bool(forKey: &quot;hasSavedGame&quot;)<br>    <br>    var body: some Scene {<br>        WindowGroup {<br>            MenuView(hasSavedGame: $hasSavedGame, gameManager: gameManager, startGame: { newGame in<br>                if newGame {<br>                    gameManager.setupGame()<br>                }<br>                isShowingGameView = true<br>            })<br>            .onChange(of: scenePhase) { _, newPhase in<br>                if newPhase == .background || newPhase == .inactive {<br>                    gameManager.saveGameState()<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The scenePhase environment detects when the app enters the background or foreground.</li><li>The app starts with MenuView, where users can choose to continue a saved game or start a new one.</li><li>UserDefaults helps track if a saved game exists, and the game state is saved when the app goes into the background.</li></ul><h4><strong>2. The Game Grid: Designing the Core Layout</strong></h4><p>The game’s grid is displayed using a LazyVGrid in GameGridView. This dynamically adapts the tiles’ size based on the screen’s size and user interactions (like swiping).</p><pre>struct GameGridView: View {<br>    @ObservedObject var gameManager: GameManager<br>    <br>    var body: some View {<br>        GeometryReader { geometry in<br>            let spacing: CGFloat = 15<br>            let tileSize = calculateTileSize(geometry: geometry)<br>            <br>            LazyVGrid(columns: createGridColumns(tileSize: tileSize), spacing: spacing) {<br>                ForEach(0..&lt;gameManager.grid.count, id: \.self) { row in<br>                    ForEach(0..&lt;gameManager.grid[row].count, id: \.self) { col in<br>                        TileView(tile: gameManager.grid[row][col])<br>                            .frame(width: tileSize, height: tileSize)<br>                            .onTapGesture {<br>                                handleTileTap(row: row, col: col)<br>                            }<br>                    }<br>                }<br>            }<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>The GeometryReader allows dynamic resizing of the grid based on the screen size.</li><li>LazyVGrid efficiently displays the tiles in a grid format.</li><li>User interactions such as swipes or taps on tiles are handled through gesture recognizers.</li></ul><h4><strong>3. Managing Game State: GameManager Class</strong></h4><p>The heart of the game logic lies in the GameManager class, which manages the grid, handles tile movements, and saves the game state.</p><pre>class GameManager: ObservableObject {<br>    @Published var grid: [[Tile]] = []<br>    @Published var currentScore: Int = 0<br>    <br>    init() {<br>        loadGameState()<br>    }<br>    <br>    func setupGame() {<br>        currentScore = 0<br>        initializeGrid()<br>        addRandomTile()<br>    }<br>    <br>    func saveGameState() {<br>        UserDefaults.standard.set(currentScore, forKey: &quot;currentScore&quot;)<br>        UserDefaults.standard.set(true, forKey: &quot;hasSavedGame&quot;)<br>    }<br>    <br>    func loadGameState() {<br>        currentScore = UserDefaults.standard.integer(forKey: &quot;currentScore&quot;)<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>GameManager manages the grid, score, and logic for tile merging and swiping.</li><li>The game state is saved using UserDefaults, allowing players to resume from where they left off.</li></ul><h4><strong>4. Animating the Tiles: TileView Component</strong></h4><p>The TileView handles the display and animation of individual tiles. It changes the appearance based on the tile’s value or if it’s a power-up.</p><pre>struct TileView: View {<br>    var tile: Tile<br>    <br>    var body: some View {<br>        ZStack {<br>            RoundedRectangle(cornerRadius: 8)<br>                .fill(tileBackgroundColor)<br>                .aspectRatio(1, contentMode: .fit)<br>            <br>            if case let .number(value) = tile.content {<br>                Text(&quot;\(value)&quot;)<br>                    .font(.largeTitle)<br>                    .bold()<br>                    .foregroundColor(.white)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Explanation:</strong></p><ul><li>Tiles are displayed as RoundedRectangle shapes.</li><li>Depending on the tile’s content (number or power-up), the UI updates dynamically.</li><li>SwiftUI’s ZStack allows layering UI elements, making it easy to animate and style.</li></ul><h4><strong>5. Handling Gestures: Swipe Actions</strong></h4><p>To allow users to swipe tiles in four directions, we implemented swipe gestures in the game grid.</p><pre>.gesture(<br>    DragGesture()<br>        .onEnded { gesture in<br>            if abs(gesture.translation.width) &gt; abs(gesture.translation.height) {<br>                gameManager.swipe(direction: gesture.translation.width &gt; 0 ? .right : .left)<br>            } else {<br>                gameManager.swipe(direction: gesture.translation.height &gt; 0 ? .down : .up)<br>            }<br>        }<br>)</pre><p><strong>Explanation:</strong></p><ul><li>The DragGesture is used to detect the user’s swipe direction.</li><li>The gesture’s translation values help determine whether the swipe is vertical or horizontal, triggering the corresponding movement in the game.</li></ul><h3><strong>Conclusion</strong></h3><p>Building <strong>2048 PowerPlay</strong> with SwiftUI was a rewarding experience, allowing me to take advantage of SwiftUI’s declarative syntax and powerful state management. The project taught me a lot about building responsive layouts, managing game state, and adding animations in SwiftUI.</p><p>If you’re interested in exploring the full code or want to try building your own version of the game, you can download the full project from my GitHub repository:</p><blockquote><a href="https://github.com/AbhishekSuryawanshi/2048PowerPlay/tree/main">GitHub: 2048 PowerPlay</a></blockquote><p>Feel free to fork the project, experiment with it, and share your feedback!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=423bf8a400a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>