<?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 Mohammed Rokon Uddin on Medium]]></title>
        <description><![CDATA[Stories by Mohammed Rokon Uddin on Medium]]></description>
        <link>https://medium.com/@shoaib-rokon?source=rss-60a50a77a83c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*I0dqdoPGqEndPg8HpD4jGw.png</url>
            <title>Stories by Mohammed Rokon Uddin on Medium</title>
            <link>https://medium.com/@shoaib-rokon?source=rss-60a50a77a83c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 22:30:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@shoaib-rokon/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[FinTech iOS App Security: A Complete Engineering Guide from TLS to the Secure Enclave]]></title>
            <link>https://systemweakness.com/fintech-ios-app-security-a-complete-engineering-guide-from-tls-to-the-secure-enclave-30fa89d55a85?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/30fa89d55a85</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[fintech]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Thu, 07 May 2026 10:38:18 GMT</pubDate>
            <atom:updated>2026-05-08T08:07:24.790Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IL5_L109i3S4lDkCZfcWyw.png" /><figcaption><a href="https://unsplash.com/illustrations/woman-using-fingerprint-unlock-on-smartphone-for-phone-security-F29F9OqTOck?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Illustration</a> by <a href="https://unsplash.com/@vectorelements/illustrations?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">VectorElements</a> on <a href="https://unsplash.com/illustrations?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>How to build a production-hardened iOS payment application with real Swift code, cryptographic first principles, and the security mindset that separates senior engineers from everyone else</h4><h3>The Mental Model: Security Is a Stack</h3><p>Before a single line of Swift, understand the layering. A FinTech iOS app has at least five distinct security layers, each providing a different guarantee. If any layer is missing, the layers above it are weakened:</p><pre>┌────────────────────────────────────────┐<br>│  Layer 5: Payment &amp; Business Logic     │  ← PCI-DSS, Tokenization, Non-Repudiation<br>├────────────────────────────────────────┤<br>│  Layer 4: Session &amp; Identity           │  ← JWT, Token Rotation, Step-Up Auth<br>├────────────────────────────────────────┤<br>│  Layer 3: App Integrity                │  ← Jailbreak Detection, Code Signing<br>├────────────────────────────────────────┤<br>│  Layer 2: Data at Rest                 │  ← Keychain, Secure Enclave, Data Protection<br>├────────────────────────────────────────┤<br>│  Layer 1: Data in Transit              │  ← TLS 1.3, Certificate Pinning, ATS<br>└────────────────────────────────────────┘</pre><h3>Part 1: Securing the Wire — URLSession, TLS 1.3, and Certificate Pinning</h3><h4>URLSession Is Not Just an HTTP Client</h4><p>URLSession manages your entire security surface for network communication: connection pooling, credential storage, cookie persistence, and the TLS handshake lifecycle. The configuration you choose determines whether sensitive response data lands on disk or stays in memory. For a payment app, that distinction is critical.</p><pre>// The three configurations — choose deliberately<br>let payConfig = URLSessionConfiguration.ephemeral<br>// ✓ No disk cache. No cookie persistence. No credential storage.<br>// Everything lives in memory and vanishes when the session is invalidated.<br><br>let defaultConfig = URLSessionConfiguration.default<br>// ✗ Writes response data to disk cache. Auth tokens can survive app restarts.<br>// Never use this for financial API endpoints.<br><br>let bgConfig = URLSessionConfiguration.background(withIdentifier: &quot;com.app.kyc-upload&quot;)<br>// ✓ For large uploads (KYC documents) that must survive app termination.<br>// Understand: this writes to disk. Use it only for non-sensitive bulk transfers</pre><p>There is a subtler trap that catches most developers: <strong>URLSession.shared cannot do certificate pinning.</strong> The shared session is created with a nil delegate, and because the delegate is copied at initialization, you cannot assign one after the fact. If your app is doing anything security-sensitive on URLSession.shared, you have no pinning — any certificate from any CA will be silently accepted.</p><p>Production setup for a payment session looks like this:</p><pre>final class NetworkSession {<br>    static let shared = NetworkSession()<br><br>    let paymentSession: URLSession<br><br>    private init() {<br>        let config = URLSessionConfiguration.ephemeral<br><br>        // Belt-and-suspenders: disable caching at both the request and session level<br>        config.requestCachePolicy = .reloadIgnoringLocalAndRemoteCacheData<br>        config.urlCache = nil<br><br>        // Fail fast for payment UX — don&#39;t leave users hanging<br>        config.timeoutIntervalForRequest  = 30<br>        config.timeoutIntervalForResource = 60<br><br>        // We manage auth via Authorization header, not cookies<br>        config.httpCookieAcceptPolicy = .never<br>        config.httpShouldSetCookies   = false<br>        config.httpCookieStorage      = nil<br><br>        // Security and idempotency headers on every request<br>        config.httpAdditionalHeaders = [<br>            &quot;X-App-Version&quot;: Bundle.main.appVersion,<br>            &quot;X-Platform&quot;:    &quot;iOS&quot;,<br>            &quot;X-Request-ID&quot;:  UUID().uuidString  // idempotency key<br>        ]<br><br>        // Custom delegate is mandatory for certificate pinning<br>        self.paymentSession = URLSession(<br>            configuration: config,<br>            delegate: PinningDelegate(),<br>            delegateQueue: nil<br>        )<br>    }<br>}</pre><h4>TLS 1.3 — Understanding What Protects Your Data</h4><p>TLS 1.3 (RFC 8446) is the protocol that encrypts every byte between your app and your server. Understanding it at the handshake level — not just “we use HTTPS” — separates engineers who can defend architectural decisions from those who can’t.</p><p><strong>What TLS actually guarantees:</strong></p><ul><li><strong>Confidentiality</strong> — Data is encrypted. Eavesdroppers see ciphertext.</li><li><strong>Integrity</strong> — Any modification in transit is detected. An attacker cannot flip a transaction amount without the server rejecting the message.</li><li><strong>Authentication</strong> — You’re talking to the real server, not an impostor.</li></ul><p>All three are required. Confidentiality without integrity is dangerous: an attacker who cannot <em>read</em> your data can still <em>corrupt</em> it.</p><p><strong>The TLS 1.3 handshake in one breath:<br></strong>The key innovation in TLS 1.3 is that the client sends its ECDH key share <em>in the first message</em>. The server can immediately derive shared keys and begin encrypting its response. The result is a <strong>1-RTT</strong> handshake — compared to 2-RTT in TLS 1.2 — and the certificate is now transmitted encrypted, not in plaintext.</p><pre>Client                                     Server<br>  │──── ClientHello (+ ECDH key share) ────►│<br>  │◄═══ ServerHello + Certificate           │  ← Encrypted from here<br>  │◄═══ {CertificateVerify} ════════════════│  ← Server signs w/ private key<br>  │◄═══ {Finished} ═════════════════════════│<br>  │════ {Finished} ═════════════════════════►│<br>  │════ {Application Data} ═════════════════►│  ← 1 RTT total</pre><p><strong>Perfect Forward Secrecy — why it matters for payment data:<br></strong>TLS 1.3 makes PFS mandatory by using ECDHE (Elliptic Curve Diffie-Hellman Ephemeral). Each session generates a new ephemeral key pair. The shared secret is derived and immediately discarded. No session key is ever stored.</p><p>The threat scenario without PFS: an attacker records all your encrypted traffic today. Six months from now, they compromise your server’s private key (breach, court order, state actor). They can now decrypt every historical session — every transaction amount, every recipient account, every balance query — going back to the beginning. With PFS, recorded traffic is permanently safe because the session keys no longer exist.</p><p><strong>The one TLS 1.3 trap to memorize: 0-RTT resumption<br></strong>TLS 1.3 allows returning clients to send application data before the handshake completes using a pre-shared key. Zero round trips. It sounds attractive for latency, but <strong>0-RTT data is vulnerable to replay attacks</strong>: an intercepted request can be re-submitted verbatim. For a POST /transfer endpoint, this could mean a payment executes twice.</p><p>Never enable 0-RTT for any mutating endpoint. Only for idempotent GETs of static content.</p><p>To enforce TLS 1.3 programmatically via Apple’s Network framework:</p><pre>import Network<br><br>let tlsOptions = NWProtocolTLS.Options()<br>sec_protocol_options_set_min_tls_protocol_version(<br>    tlsOptions.securityProtocolOptions,<br>    .TLSv13<br>)<br>let params = NWParameters(tls: tlsOptions)<br>let connection = NWConnection(host: &quot;api.fintech.com&quot;, port: 443, using: params)</pre><h4>Certificate Pinning — Three Methods, One Goal</h4><p>Standard TLS trusts any certificate signed by any of the hundreds of Certificate Authorities in the device trust store. A compromised or malicious CA can issue a valid certificate for your domain — and your app will accept it. Certificate pinning breaks this assumption by hardcoding expected cryptographic values and validating them on every handshake.</p><p><strong>Method 1: Full Certificate Pinning</strong> Pin the entire DER-encoded certificate. Maximum specificity. Breaks on every certificate renewal.</p><p><strong>Method 2: Public Key (SPKI) Pinning</strong> ← <em>Recommended for production</em> Pin the SHA-256 hash of the SubjectPublicKeyInfo — the public key and its algorithm metadata. Survives certificate renewals as long as the key pair is reused. Extract the pin with:</p><pre>openssl s_client -connect api.fintech.com:443 2&gt;/dev/null \<br>  | openssl x509 -pubkey -noout \<br>  | openssl pkey -pubin -outform der \<br>  | openssl dgst -sha256 -binary \<br>  | base64</pre><p><strong>Method 3: CA/Intermediate Pinning</strong> Pin the issuing CA. More flexible but trusts the entire CA hierarchy. Only appropriate if you run your own internal CA.</p><p>Here is a production-grade SPKI pinning delegate:</p><pre>import CryptoKit<br>import Security<br><br>final class SPKIPinner: NSObject, URLSessionDelegate {<br><br>    // Always pin at minimum 2 hashes: current + backup for rotation<br>    private static let pins: [String: Set&lt;String&gt;] = [<br>        &quot;api.fintech.com&quot;: [<br>            &quot;47DEQpj8HBSa+/TImW+5JCeuQeRkm5NMpJWZG3hSuFU=&quot;,  // current<br>            &quot;CXVN1p2FqLGh7asDFdxf5Mg7xqxz7VBrKJpb4R3qZtY=&quot;   // backup<br>        ]<br>    ]<br><br>    // ASN.1 header for EC keys — must be prepended before hashing<br>    private static let ecHeaderBytes: [UInt8] = [<br>        0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86,<br>        0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a,<br>        0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00<br>    ]<br><br>    func urlSession(<br>        _ session: URLSession,<br>        didReceive challenge: URLAuthenticationChallenge,<br>        completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -&gt; Void<br>    ) {<br>        guard<br>            challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,<br>            let serverTrust = challenge.protectionSpace.serverTrust<br>        else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br><br>        // Step 1: Standard chain validation (expiry, revocation, CA chain)<br>        var cfError: CFError?<br>        guard SecTrustEvaluateWithError(serverTrust, &amp;cfError) else {<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br><br>        // Step 2: Custom SPKI pin validation on top of standard TLS<br>        guard validateSPKIPin(serverTrust: serverTrust, host: challenge.protectionSpace.host) else {<br>            SecurityTelemetry.report(event: .pinFailure(host: challenge.protectionSpace.host))<br>            completionHandler(.cancelAuthenticationChallenge, nil)<br>            return<br>        }<br><br>        completionHandler(.useCredential, URLCredential(trust: serverTrust))<br>    }<br><br>    private func validateSPKIPin(serverTrust: SecTrust, host: String) -&gt; Bool {<br>        guard let expectedPins = SPKIPinner.pins[host],<br>              let cert       = SecTrustGetCertificateAtIndex(serverTrust, 0),<br>              let publicKey  = SecCertificateCopyKey(cert),<br>              let rawKeyData = SecKeyCopyExternalRepresentation(publicKey, nil) as Data?<br>        else { return false }<br><br>        var spki = Data(SPKIPinner.ecHeaderBytes)<br>        spki.append(rawKeyData)<br><br>        let hash       = SHA256.hash(data: spki)<br>        let hashBase64 = Data(hash).base64EncodedString()<br><br>        return expectedPins.contains(hashBase64)<br>    }<br>}</pre><p><strong>The operational reality: pin rotation<br></strong>Pinning creates an operational hazard — a certificate change without a corresponding app update bricks your users. The strategy:</p><ol><li>Always ship <strong>N+1 pins</strong>: the current key hash AND the hash of the next key pair, before you rotate.</li><li>Serve the upcoming pin in a signed API response <em>before</em> the rotation date. App versions can learn the next pin dynamically.</li><li>Enforce a minimum app version after rotation. Return 426 Upgrade Required to old versions.</li><li>Have an emergency kill switch: a time-limited, server-signed flag that disables pinning enforcement. Fetched via an alternate channel. Only for catastrophic failure scenarios.</li></ol><h4>App Transport Security — Harden the Policy Layer</h4><p>ATS is Apple’s network security policy, enforced at the OS level before your code runs. The defaults are reasonable, but a payment app should harden further:</p><pre>&lt;!-- Info.plist — Production ATS for a FinTech app --&gt;<br>&lt;key&gt;NSAppTransportSecurity&lt;/key&gt;<br>&lt;dict&gt;<br>    &lt;!-- Never. Not even for a &quot;temporary&quot; developer convenience. --&gt;<br>    &lt;key&gt;NSAllowsArbitraryLoads&lt;/key&gt;<br>    &lt;false/&gt;<br><br>    &lt;key&gt;NSExceptionDomains&lt;/key&gt;<br>    &lt;dict&gt;<br>        &lt;key&gt;api.fintech.com&lt;/key&gt;<br>        &lt;dict&gt;<br>            &lt;!-- TLS 1.3 minimum — iOS 12.2+ --&gt;<br>            &lt;key&gt;NSExceptionMinimumTLSVersion&lt;/key&gt;<br>            &lt;string&gt;TLSv1.3&lt;/string&gt;<br><br>            &lt;!-- ECDHE cipher suites only — enforces PFS --&gt;<br>            &lt;key&gt;NSExceptionRequiresForwardSecrecy&lt;/key&gt;<br>            &lt;true/&gt;<br><br>            &lt;!-- Require cert to appear in Certificate Transparency logs --&gt;<br>            &lt;key&gt;NSRequiresCertificateTransparency&lt;/key&gt;<br>            &lt;true/&gt;<br><br>            &lt;key&gt;NSIncludesSubdomains&lt;/key&gt;<br>            &lt;true/&gt;<br>        &lt;/dict&gt;<br>    &lt;/dict&gt;<br>&lt;/dict&gt;</pre><p>NSRequiresCertificateTransparency is worth calling out: it forces iOS to verify that the server&#39;s certificate is logged in a public CT ledger. This prevents &quot;private&quot; certificate issuance by a CA — a rogue cert for your domain that was never publicly logged will be rejected by the OS before your URLSession delegate even fires.</p><h4>Concurrency: The Double Token Refresh Race Condition</h4><p>There is a class of bug that exists in virtually every payment app using refresh tokens and callback-based networking. Two concurrent requests — say, a balance check and a transaction history load — both receive a 401 Unauthorized at the same moment. Both detect an expired token. Both trigger a refresh simultaneously. The server processes both, invalidating the old refresh token twice. Depending on timing, one or both calls end up orphaned, and the user is silently logged out.</p><p>Swift actors solve this elegantly with compile-time enforcement:</p><pre>actor TokenStore {<br>    private var accessToken: String?<br>    private var expiresAt:   Date?<br>    // This task reference is the key to serialization<br>    private var refreshTask: Task&lt;String, Error&gt;?<br><br>    func validToken(using refresher: TokenRefresher) async throws -&gt; String {<br>        // Fast path: valid token in memory<br>        if let token = accessToken,<br>           let expiry = expiresAt,<br>           expiry &gt; Date().addingTimeInterval(60) {<br>            return token<br>        }<br><br>        // Critical: if a refresh is already in-flight, JOIN it.<br>        // Don&#39;t start a second one. All callers await the same Task.<br>        if let existing = refreshTask {<br>            return try await existing.value<br>        }<br><br>        // Start exactly one refresh<br>        let task = Task&lt;String, Error&gt; {<br>            let refreshToken = try KeychainService.load(key: .refreshToken)<br>            let response     = try await refresher.refresh(token: refreshToken)<br>            try KeychainService.save(response.refreshToken, key: .refreshToken)<br>            await self.setToken(response.accessToken, expiresIn: response.expiresIn)<br>            return response.accessToken<br>        }<br>        refreshTask = task<br><br>        do {<br>            let result = try await task.value<br>            refreshTask = nil<br>            return result<br>        } catch {<br>            refreshTask = nil<br>            throw error<br>        }<br>    }<br>}</pre><p>The actor’s serial execution model makes the race condition structurally impossible. The compiler enforces it — you cannot access actor-isolated state without await, and the actor guarantees only one execution context enters at a time.</p><h3>Part 2: Data at Rest — Keychain, Cryptography, and the Secure Enclave</h3><h4>Keychain: Not All Storage Is Equal</h4><p>The Keychain is the correct place for all sensitive data in an iOS app. But the Keychain is not a simple database — it has a protection class system that determines when item keys are available, tied to the device hardware and the user’s passcode.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*onm40iKjTf3G6lUUHrr_dw.png" /><figcaption>The accessibility attribute is the most consequential choice you make</figcaption></figure><p>The ThisDeviceOnly variants are critical: they exclude items from iCloud Keychain sync, iCloud backups, and device migration. A payment session token should never silently appear on a user&#39;s new iPhone. If it does, your device-binding and registration checks are worthless.</p><pre>final class KeychainService {<br>    private static let service     = &quot;com.fintech.ios&quot;<br>    private static let accessGroup = &quot;TEAMID.com.fintech.shared&quot;<br><br>    static func save(_ data: Data, key: KeychainKey) throws {<br>        deleteIfExists(key: key)  // Prevent -25299 duplicate item error<br><br>        let query: [CFString: Any] = [<br>            kSecClass:              kSecClassGenericPassword,<br>            kSecAttrService:        service,<br>            kSecAttrAccount:        key.rawValue,<br>            kSecValueData:          data,<br>            kSecAttrAccessible:     kSecAttrAccessibleWhenUnlockedThisDeviceOnly,<br>            kSecAttrSynchronizable: kCFBooleanFalse!,<br>            kSecAttrAccessGroup:    accessGroup<br>        ]<br><br>        let status = SecItemAdd(query as CFDictionary, nil)<br>        guard status == errSecSuccess else {<br>            throw KeychainError.saveFailed(status)<br>        }<br>    }<br>}</pre><p><strong>The Keychain persistence gotcha:</strong> Items persist after app deletion by default. A fresh install can read items written by a previous install. On first launch, check for a “clean install” marker in UserDefaults (which <em>is</em> cleared on delete). If UserDefaults is empty but the Keychain has data, you have stale credentials from a prior install — wipe the Keychain.</p><h4>Cryptography: AES-GCM, ECDH, HMAC, and RSA</h4><p>Apple’s CryptoKit makes safe cryptography remarkably ergonomic. Here are the patterns that matter in a payment app.</p><p><strong>AES-256-GCM: Authenticated Encryption<br></strong>GCM (Galois/Counter Mode) is an AEAD — Authenticated Encryption with Associated Data. One operation provides both confidentiality and integrity. The 16-byte authentication tag prevents any modification of the ciphertext from going undetected. Use this everywhere. Never use AES-CBC for new code — it provides confidentiality only and is vulnerable to padding oracle attacks.</p><pre>import CryptoKit<br><br>// Encrypt a transaction payload before transmission<br>func encrypt(_ plaintext: Data, key: SymmetricKey) throws -&gt; EncryptedEnvelope {<br>    // CryptoKit generates a cryptographically random 12-byte nonce automatically.<br>    // NEVER reuse a nonce with the same key — catastrophic in GCM.<br>    // Nonce reuse with the same key allows an attacker to XOR ciphertexts<br>    // and recover plaintext, plus forge authentication tags.<br>    let nonce = try AES.GCM.Nonce()<br><br>    let sealed = try AES.GCM.seal(plaintext, using: key, nonce: nonce)<br><br>    return EncryptedEnvelope(<br>        nonce:      Data(nonce),<br>        ciphertext: sealed.ciphertext,<br>        tag:        sealed.tag         // 16 bytes — detects any tampering<br>    )<br>}<br><br>// Decrypt — throws CryptoKitError.authenticationFailure if tampered<br>func decrypt(_ envelope: EncryptedEnvelope, key: SymmetricKey) throws -&gt; Data {<br>    let nonce     = try AES.GCM.Nonce(data: envelope.nonce)<br>    let sealedBox = try AES.GCM.SealedBox(<br>        nonce:      nonce,<br>        ciphertext: envelope.ciphertext,<br>        tag:        envelope.tag<br>    )<br>    return try AES.GCM.open(sealedBox, using: key)<br>    // If the tag doesn&#39;t match, this throws. It does not silently return wrong data.<br>}</pre><p><strong>ECDH + HKDF: Session Key Establishment<br></strong>When you need to establish a shared encryption key with the server — for something like end-to-end encrypting a PIN change — ECDH lets both parties compute the same secret without transmitting it. The security rests on the Elliptic Curve Discrete Logarithm Problem: an attacker observing both public keys cannot derive the shared secret.</p><pre>import CryptoKit<br><br>// Client-side: generate ephemeral key pair for this session only<br>let clientPrivKey = P256.KeyAgreement.PrivateKey()  // ephemeral — discarded after<br><br>// Send clientPrivKey.publicKey.rawRepresentation to server<br>// Receive serverPublicKeyData from server<br><br>let serverPubKey  = try P256.KeyAgreement.PublicKey(<br>    rawRepresentation: serverPublicKeyData<br>)<br><br>// ECDH: compute shared secret<br>let sharedSecret = try clientPrivKey.sharedSecretFromKeyAgreement(with: serverPubKey)<br><br>// HKDF derivation — NEVER use the raw shared secret directly as an AES key.<br>// The ECDH output has mathematical structure. HKDF &quot;randomizes&quot; it into<br>// a uniform bit string suitable as a cryptographic key.<br>// The sharedInfo parameter binds the key to this specific session ID.<br>let sessionKey = sharedSecret.hkdfDerivedSymmetricKey(<br>    using: SHA256.self,<br>    salt:       &quot;fintech-session-v1&quot;.data(using: .utf8)!,<br>    sharedInfo: sessionId.data(using: .utf8)!,<br>    outputByteCount: 32  // 256-bit AES key<br>)<br>// Both client and server derive identical keys. The secret was never transmitted.</pre><p><strong>HMAC: API Request Signing<br></strong>Every API request should carry an HMAC-SHA256 signature over a canonical representation of the request. This proves the request came from a holder of the shared secret and was not modified after signing.</p><pre>// Canonical request string — both client and server must produce identical bytes<br>// Format: METHOD\nPATH\nTIMESTAMP\nNONCE\nSHA256(body_hex)<br>let canonical = [&quot;POST&quot;, &quot;/api/v3/transfer&quot;,<br>                  String(timestamp), nonce,<br>                  SHA256.hash(data: bodyData).hexString]<br>    .joined(separator: &quot;\n&quot;)<br><br>let key = MockBackend.hmacSecret  // shared secret from device registration<br>let mac = HMAC&lt;SHA256&gt;.authenticationCode(<br>    for: canonical.data(using: .utf8)!,<br>    using: key<br>)<br>// Send as: X-Fintech-Signature: &lt;hex string&gt;<br><br>// Server-side verification — constant-time comparison prevents timing attacks<br>let valid = HMAC&lt;SHA256&gt;.isValidAuthenticationCode(<br>    receivedMACBytes,        // received from client<br>    authenticating: canonical.data(using: .utf8)!,<br>    using: key<br>)<br>// isValidAuthenticationCode always takes the same time regardless of where<br>// a mismatch occurs — prevents attackers from guessing bytes via response time.</pre><p><strong>RSA-OAEP: Key Wrapping<br></strong>RSA is not for encrypting data — it’s slow and limited to roughly 190 bytes at 2048-bit. RSA is for <em>key wrapping</em>: encrypting a freshly generated AES key with the server’s public key so only the server can recover it. The hybrid pattern is: <strong>RSA wraps the AES key → AES encrypts the data</strong>.</p><p>Always use rsaEncryptionOAEPSHA256. Never rsaEncryptionPKCS1 — Bleichenbacher&#39;s 1998 padding oracle attack is still practical against PKCS#1 v1.5 implementations.</p><pre>let algorithm = SecKeyAlgorithm.rsaEncryptionOAEPSHA256<br>var error: Unmanaged&lt;CFError&gt;?<br><br>// Wrap: encrypt AES key bytes with server&#39;s RSA public key<br>let wrappedKey = SecKeyCreateEncryptedData(<br>    serverPublicKey,<br>    algorithm,<br>    aesKeyBytes as CFData,<br>    &amp;error<br>) as Data?<br><br>// OAEP output size = RSA key size = 256 bytes for RSA-2048, always<br>// OAEP is probabilistic: same input → different output every time<br>// This is a feature. PKCS#1 v1.5 is deterministic — a weakness.<br><br>// Unwrap: server uses private key<br>let unwrapped = SecKeyCreateDecryptedData(<br>    serverPrivateKey,<br>    algorithm,<br>    wrappedKey! as CFData,<br>    &amp;error<br>) as Data?</pre><h4>The Secure Enclave: Hardware-Level Security</h4><p>The Secure Enclave is a dedicated coprocessor in every Apple device with an A7 chip or later. It has its own encrypted memory, its own boot ROM, and its own cryptographic engine. When you generate a P-256 key pair inside the Secure Enclave, the private key <strong>never leaves the chip</strong> — not even the main CPU, the OS, or your code can read it. Signing operations are performed inside the enclave; only the signature exits.</p><p>This changes the threat model fundamentally. Even a fully compromised iOS device cannot produce a valid transaction signature without the user’s biometric.</p><pre>import CryptoKit<br>import Security<br><br>// Device registration: generate hardware-bound key pair<br>// .biometryCurrentSet: Face ID required AND key invalidated if enrollment changes.<br>// If someone adds their fingerprint after theft, the key becomes inaccessible.<br>let access = SecAccessControlCreateWithFlags(<br>    kCFAllocatorDefault,<br>    kSecAttrAccessibleWhenUnlockedThisDeviceOnly,<br>    [.privateKeyUsage, .biometryCurrentSet],<br>    nil<br>)!<br><br>let privateKey = try SecureEnclave.P256.Signing.PrivateKey(accessControl: access)<br><br>// Store the opaque data representation in Keychain.<br>// This is NOT the raw private key — it&#39;s a hardware handle.<br>// Without this handle, you cannot reference the SE key again.<br>// With the handle but without the biometric, the SE won&#39;t sign.<br>let handleData = privateKey.dataRepresentation<br>try KeychainService.save(handleData, key: .deviceSigningKey)<br><br>// Upload the public key to your server during registration<br>let publicKeyForServer = privateKey.publicKey.rawRepresentation<br><br>// ── Transaction signing ──────────────────────────────────────────<br><br>// Load key from stored handle (no biometric required to load, only to use)<br>let restoredKey = try SecureEnclave.P256.Signing.PrivateKey(<br>    dataRepresentation: storedHandleData<br>)<br><br>// Construct canonical transaction bytes — what we&#39;re actually signing<br>// Both client and server must produce identical bytes from the same fields.<br>// Amount as integer paisa: never use Double for money.<br>// 0.1 + 0.2 = 0.30000000000000004 in IEEE 754. That&#39;s not a transaction amount.<br>let canonical = [<br>    transactionId,<br>    senderWallet,<br>    receiverWallet,<br>    String(amountPaisa),     // ← Int64 paisa, not Double BDT<br>    String(timestampUnix),<br>    serverIssuedNonce,       // prevents replay attacks<br>    currency<br>].joined(separator: &quot;|&quot;).data(using: .utf8)!<br><br>// This call triggers Face ID on a real device.<br>// The biometric prompt is shown by Secure Enclave hardware — not your UI code.<br>// Even on a jailbroken device, this cannot be bypassed without the user&#39;s face/fingerprint.<br>let signature = try restoredKey.signature(for: canonical)<br>// Returns DER-encoded ECDSA P-256 signature (~70-72 bytes)<br><br>// Server-side verification — stateless, only needs the public key<br>let pubKey    = try P256.Signing.PublicKey(rawRepresentation: storedPublicKey)<br>let sig       = try P256.Signing.ECDSASignature(derRepresentation: signature.derRepresentation)<br>let isValid   = pubKey.isValidSignature(sig, for: canonical)<br>// isValid = true → non-repudiation established.<br>// The user cannot credibly deny this transaction.</pre><h3>Part 3: Payment Layer Security</h3><h4><strong>PCI-DSS — What Actually Applies to Your iOS Code</strong></h4><p>PCI-DSS is the security standard for any system handling payment card data. The mobile app is in scope if it touches card numbers, expiry dates, or CVVs. The strategic goal is to <strong>minimize what your code ever sees</strong>.</p><p>The most important requirements that touch iOS code:</p><p><strong>Req 3 — Never store the PAN:</strong> Not encrypted, not hashed — not at all. Store a token. Display only the last four digits. Never store CVV under any circumstance, even temporarily.</p><p><strong>Req 4 — Encrypt in transit:</strong> TLS 1.2+ minimum (TLS 1.3 recommended). Your ATS configuration, certificate pinning, and ephemeral URLSession directly satisfy this.</p><p><strong>Req 6 — Secure development:</strong> OWASP Mobile Top 10 coverage is explicitly required in PCI DSS v4.0. SAST scanning on every build. Security review checklist on every pull request touching payment flows.</p><p><strong>Req 10 — Log everything, but never log card data:</strong> A log file containing a PAN is itself in PCI scope. Your logging layer must scrub sensitive patterns before writing:</p><pre>final class SecureLogger {<br>    private static let scrubPatterns: [(pattern: String, replacement: String)] = [<br>        (#&quot;\b\d{13,19}\b&quot;#,                    &quot;[CARD_REDACTED]&quot;),   // PAN<br>        (#&quot;&quot;pin&quot;\s*:\s*&quot;[^&quot;]+&quot;&quot;#,              #&quot;&quot;pin&quot;:&quot;[REDACTED]&quot;#),<br>        (#&quot;&quot;otp&quot;\s*:\s*&quot;[^&quot;]+&quot;&quot;#,              #&quot;&quot;otp&quot;:&quot;[REDACTED]&quot;#),<br>        (&quot;Bearer [A-Za-z0-9._-]+&quot;,             &quot;Bearer [TOKEN]&quot;)<br>    ]<br><br>    static func log(_ message: String) {<br>        var safe = message<br>        for (pattern, replacement) in scrubPatterns {<br>            if let regex = try? NSRegularExpression(pattern: pattern) {<br>                safe = regex.stringByReplacingMatches(<br>                    in: safe,<br>                    range: NSRange(safe.startIndex..., in: safe),<br>                    withTemplate: replacement<br>                )<br>            }<br>        }<br>        // Now safe to write to OSLog<br>        os_log(&quot;%{public}@&quot;, safe)<br>    }<br>}</pre><h4>Tokenization vs. Encryption — A Critical Distinction</h4><p>These are not interchangeable. Understanding the difference is fundamental to designing a secure payment architecture.</p><p><strong>Encryption</strong> is reversible with a key. If your key is compromised — through a breach, an extraction attack on a jailbroken device, or an insider — every encrypted record is exposed. Encryption protects data from eavesdroppers. It does not protect data from someone who compromises the system holding the key.</p><p><strong>Tokenization</strong> replaces a card number with a random, meaningless token. The mapping lives in a separate, isolated token vault — a PCI Level 1 certified system your app never communicates with directly. Even if your app is fully compromised, an attacker retrieves tokens. A token like pm_1A2B3C4D5E without access to the vault is permanently useless.</p><p>The implementation principle: <strong>never let raw card data touch your code.</strong> Use a PCI-validated SDK (Stripe, Adyen, Checkout.com) that presents its own UI for card entry. The SDK submits the card directly to the gateway and hands your code a token. Your server stores the token, not the PAN. Your app uses the token for all subsequent operations.</p><h4>OTP, HOTP, and TOTP — From First Principles</h4><p>Understanding the algorithm behind your OTP system means you can defend it in code review and explain what breaks if you get it wrong.</p><p><strong>HOTP (RFC 4226)</strong> is counter-based: HOTP(secret, counter) = Truncate(HMAC-SHA1(secret, counter))</p><p>Both client and server share an incrementing counter. The risk: counter desynchronization. If the user generates codes without submitting them, the client counter advances while the server counter doesn’t.</p><p><strong>TOTP (RFC 6238)</strong> replaces the incrementing counter with a time-derived counter: counter = floor(unix_time / 30)</p><p>Both parties compute the same counter from wall-clock time. No synchronization needed — only clock agreement (with ±1 window tolerance for skew).</p><h4>Session Management — The JWT Architecture That Doesn’t Fail</h4><p>JWTs are not inherently secure. The security comes from the <em>architecture</em> around them.</p><p>A production FinTech session uses three token types:</p><p><strong>Access Token (JWT)</strong> — Short-lived (15 minutes). In-memory only — never written to disk. Sent in every API request as a Bearer token. Contains: sub (user ID), walletId, deviceId, exp, iat, roles, sessionId.</p><p><strong>Refresh Token</strong> — Long-lived (7–30 days). Opaque random string, not a JWT. Stored in Keychain with WhenUnlockedThisDeviceOnly. Single-use with rotation: each refresh call invalidates the old token and issues a new one. If a server sees an old refresh token presented again, it revokes the entire token family and forces re-login. This detects and limits the damage from stolen refresh tokens.</p><p><strong>Step-Up Authorization Token</strong> — Very short-lived (2 minutes). Issued after biometric re-confirmation. Required for transactions above a threshold. A stolen session cannot drain an account — the attacker needs the user’s biometric too.</p><pre>actor SessionService {<br>    // Access token: in memory only. Never write to disk.<br>    private var accessToken:    String?<br>    private var accessTokenExp: Date?<br><br>    // Refresh serialization: prevents the double-refresh race<br>    private var refreshTask: Task&lt;String, Error&gt;?<br><br>    func validAccessToken() async throws -&gt; String {<br>        // 60-second safety buffer before actual expiry<br>        if let token = accessToken,<br>           let expiry = accessTokenExp,<br>           expiry &gt; Date().addingTimeInterval(60) {<br>            return token<br>        }<br><br>        // Join an in-flight refresh rather than starting another<br>        if let existing = refreshTask {<br>            return try await existing.value<br>        }<br><br>        let task = Task&lt;String, Error&gt; {<br>            let refreshToken = try KeychainService.load(key: .refreshToken)<br>            let bundle       = try await AuthBackend.refresh(token: refreshToken)<br><br>            // ROTATION: the new refresh token replaces the old one.<br>            // Server invalidates the old token. If it&#39;s replayed: alarm.<br>            try KeychainService.save(bundle.refreshToken, key: .refreshToken)<br>            await self.store(accessToken: bundle.accessToken, expiresIn: bundle.expiresIn)<br>            return bundle.accessToken<br>        }<br>        refreshTask = task<br><br>        do {<br>            let result  = try await task.value<br>            refreshTask = nil<br>            return result<br>        } catch {<br>            refreshTask  = nil<br>            await logout()   // genuine refresh failure = session is dead<br>            throw SessionError.sessionExpired<br>        }<br>    }<br><br>    func logout() async {<br>        accessToken    = nil<br>        accessTokenExp = nil<br>        refreshTask    = nil<br>        KeychainService.wipeSessionData()<br>        // Post notification to UI layer to show login screen<br>        NotificationCenter.default.post(name: .sessionExpired, object: nil)<br>    }<br>}</pre><p>One architectural note on JWTs that is frequently misunderstood: the JWT payload is base64url-encoded, not encrypted. Anyone who intercepts a JWT can decode and read all the claims without a key. Never put a PIN, card number, balance, or any sensitive value in a JWT payload. The security property of a JWT is in the <em>signature</em> — proving the token came from your auth server — not in the confidentiality of its contents.</p><h3>Part 4: Runtime Integrity — Defending Against Reverse Engineering</h3><h4>Jailbreak Detection: Defense in Depth</h4><p>A jailbroken device has its security model broken. The sandbox is bypassed. Frida can hook any function at runtime. SSL Kill Switch 2 can override certificate pinning entirely. For a payment app, a jailbroken device is a hostile environment that you cannot trust.</p><p>No single detection signal is reliable — each can be bypassed individually on a sufficiently motivated adversary. The strategy is to layer many diverse signals so the cost of bypassing all of them is prohibitively high:</p><pre>enum JailbreakDetector {<br>    static func isCompromised() -&gt; Bool {<br>        // 1. Known jailbreak filesystem artifacts<br>        let jailbreakPaths = [<br>            &quot;/Applications/Cydia.app&quot;, &quot;/Applications/Sileo.app&quot;,<br>            &quot;/usr/sbin/sshd&quot;, &quot;/bin/bash&quot;, &quot;/etc/apt&quot;,<br>            &quot;/var/jb&quot;,                          // rootless jailbreak (Dopamine, etc.)<br>            &quot;/usr/lib/libhooker.dylib&quot;,          // LibHooker<br>            &quot;/usr/lib/TweakInject.dylib&quot;         // TweakInject<br>        ]<br>        if jailbreakPaths.contains(where: FileManager.default.fileExists(atPath:)) {<br>            return true<br>        }<br>        // 2. Sandbox escape: apps cannot write to /private/var on stock iOS<br>        let testPath = &quot;/private/var/mobile/jb_probe_\(arc4random())&quot;<br>        if (try? &quot;test&quot;.write(toFile: testPath, atomically: true, encoding: .utf8)) != nil {<br>            try? FileManager.default.removeItem(atPath: testPath)<br>            return true<br>        }<br>        // 3. Injected hooking libraries (Substrate, Frida, SSL Kill Switch)<br>        let suspiciousLibs = [&quot;SubstrateLoader&quot;, &quot;frida&quot;, &quot;SSLKillSwitch&quot;,<br>                               &quot;libhooker&quot;, &quot;cycript&quot;, &quot;TweakInject&quot;]<br>        let imageCount = _dyld_image_count()<br>        for i in 0..&lt;UInt32(imageCount) {<br>            if let name = _dyld_get_image_name(i) {<br>                let imgName = String(cString: name).lowercased()<br>                if suspiciousLibs.contains(where: imgName.contains) {<br>                    return true<br>                }<br>            }<br>        }<br>        // 4. fork() entitlement: App Store apps cannot fork<br>        let pid = fork()<br>        if pid &gt;= 0 {<br>            if pid &gt; 0 { kill(pid, SIGTERM) }<br>            return true<br>        }<br>        // 5. Debugger detection via sysctl<br>        var info = kinfo_proc()<br>        var size = MemoryLayout&lt;kinfo_proc&gt;.stride<br>        var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]<br>        sysctl(&amp;mib, 4, &amp;info, &amp;size, nil, 0)<br>        if (info.kp_proc.p_flag &amp; P_TRACED) != 0 { return true }<br>        return false<br>    }<br>}</pre><p><strong>What attackers do to bypass this:</strong> A Frida script can hook the isCompromised function by name and always return false. The countermeasures: don&#39;t name your function isCompromised. Distribute the checks throughout the codebase rather than concentrating them in one place. Use C-level functions where possible — they&#39;re harder to swizzle than Swift methods. Combine with commercial obfuscation (Guardsquare iXGuard) for production. And run checks not just at launch but immediately before every transaction.</p><h3>Part 5: The OWASP Mobile Top 10 — Mapped to Your Codebase</h3><p>OWASP Mobile Top 10 2024 is not an abstract checklist. Each entry is a concrete failure mode with a concrete fix. PCI DSS v4.0 Requirement 6.3 explicitly requires addressing this list.</p><p><strong>M1 — Improper Credential Usage:</strong> Hardcoded API keys in source code. An attacker runs strings YourApp.app/YourApp | grep -i key and finds your production secret. Fix: all secrets from secure runtime config, zero credentials in source or Info.plist.</p><p><strong>M2 — Inadequate Supply Chain Security:</strong> A dependency update silently reads the clipboard — which may contain a copied OTP. Fix: lock all dependency versions, audit each SDK’s privacy manifest (PrivacyInfo.xcprivacy), review requested entitlements.</p><p><strong>M3 — Insecure Authentication:</strong> App makes authorization decisions based on JWT claims without the server re-verifying. An attacker modifies the payload (not the signature portion — the server never checked) and gets elevated access. Fix: all authorization decisions server-side, always.</p><p><strong>M5 — Insecure Communication:</strong> No certificate pinning. A corporate MDM installs an SSL inspection certificate, and all transaction data is visible to the network operator. Fix: SPKI pinning on all payment endpoints.</p><p><strong>M6 — Inadequate Privacy Controls:</strong> Crashlytics has default settings. When the app crashes mid-transaction, the crash report includes a full UIView hierarchy dump, which contains rendered transaction amounts and wallet numbers. Fix: configure crash reporters to exclude sensitive views, implement the scrubbing logger shown above.</p><p><strong>M9 — Insecure Data Storage:</strong> Auth token in UserDefaults. On a jailbroken device, any app can read another app&#39;s UserDefaults if the sandbox is bypassed. Fix: Keychain with WhenUnlockedThisDeviceOnly, always.</p><p><strong>M10 — Insufficient Cryptography:</strong> MD5 for transaction ID generation. MD5 produces collisions — two distinct transactions can have the same ID, causing server-side confusion. Fix: Use UUID() (CSPRNG-backed on Apple platforms) for all identifiers. Use CryptoKit for all cryptography — its API physically cannot use deprecated algorithms.</p><h3>Putting It Together: The Security Timeline for a Money Transfer</h3><p>A complete secure payment flow, from user intent to transaction settlement:</p><pre>T+0s   User taps &quot;Send ৳500&quot;<br>       → JailbreakDetector.isCompromised() — abort if true<br><br>T+0.1s Biometry changed detection<br>       → Compare LAContext.evaluatedPolicyDomainState to stored value<br>       → If changed: force re-authentication before proceeding<br><br>T+0.2s Fetch server-issued nonce<br>       → POST /api/v3/nonce (HMAC-signed request)<br>       → Server returns single-use nonce (TTL: 5 minutes)<br><br>T+0.5s Build canonical transaction bytes<br>       → txId|from|to|amountPaisa|timestamp|nonce|currency (UTF-8)<br>       → Amount is Int64 paisa — no floating-point<br><br>T+0.6s Sign with Secure Enclave<br>       → SecureEnclave.P256.Signing.PrivateKey.signature(for: canonical)<br>       → Face ID prompt fires — hardware-enforced biometric confirmation<br>       → Returns DER-encoded ECDSA P-256 signature<br><br>T+1.2s Fetch valid access token<br>       → TokenStore.validToken() — refreshes transparently if within 60s buffer<br>       → Actor serializes concurrent requests — one refresh, always<br><br>T+1.3s Encrypt payload<br>       → AES.GCM.seal(transactionJSON, using: sessionKey)<br>       → Fresh nonce generated for each encryption<br><br>T+1.4s Sign the HTTP request<br>       → HMAC-SHA256(secret, canonical_request_string)<br>       → Set X-Fintech-Signature header<br><br>T+1.5s Transmit<br>       → HTTPS over TLS 1.3 with ECDHE<br>       → Certificate pinning validates on URLSession delegate<br>       → URLSessionConfiguration.ephemeral — no disk cache<br><br>T+1.8s Server processing<br>       → Verify HMAC signature<br>       → Validate nonce (consumed — cannot be replayed)<br>       → Validate timestamp (reject if &gt;5 minutes old)<br>       → AES-GCM decrypt payload (authentication tag verified)<br>       → ECDSA P-256 signature verification against registered public key<br>       → Process payment<br><br>T+2.1s Response<br>       → AES-GCM encrypted response body<br>       → Audit event logged (PCI Req 10, no CHD in log)<br><br>T+2.2s UI update<br>       → Decrypt response<br>       → Display confirmation<br>       → Wipe plaintext amounts from memory</pre><p>Every step in this chain has a specific threat it neutralizes. Jailbreak detection addresses runtime manipulation. Nonce + timestamp addresses replay. HMAC addresses tampering in transit. AES-GCM addresses eavesdropping. Certificate pinning addresses MITM. Secure Enclave signing addresses session hijacking and non-repudiation. The Keychain with ThisDeviceOnly addresses device theft. None of them is sufficient alone.</p><h3>The Demo Project</h3><p>All of the concepts in this guide — AES-GCM encryption, HMAC request signing, ECDH session key establishment, RSA key wrapping, Secure Enclave transaction signing, PCI-DSS tokenization, TOTP/OTP implementation, and JWT session management — are implemented as a complete, working SwiftUI project with a mock backend, SOLID architecture, and a Swift Testing test suite.</p><p>Each topic is an interactive tab where you can enter real transaction values, observe the cryptographic operations at each step, simulate tampering and watch the authentication fail, and read the audit log that proves no sensitive data was leaked.</p><p><strong>GitHub Repository:</strong> <a href="https://github.com/rokon-uddin/FinTechSecurityDemo.git">https://github.com/rokon-uddin/FinTechSecurityDemo.git</a></p><p>The project is structured around the principle that security knowledge should be <em>demonstrable</em>, not just declarable. Clone it, run it on a real device, and watch Face ID gate a hardware-bound transaction signature.</p><h3>Closing Thoughts</h3><p>Security in a FinTech iOS app is not a feature you add at the end. It’s a set of architectural decisions made at the beginning that either constrain or enable everything that follows. Using URLSession.shared instead of a custom delegate is not a minor convenience — it&#39;s the decision to have no certificate pinning. Using UserDefaults instead of Keychain is not laziness — it&#39;s leaving session tokens readable without the device passcode.</p><p>The engineers who are genuinely dangerous in this space are the ones who understand not just <em>what</em> the security controls are, but <em>why</em> they exist — what attack they neutralize, what happens when they’re absent, and how they interact with every other layer of the stack. That understanding is what makes the difference between an app that passes a security review and an app that actually protects real people’s money.</p><p><em>Tagged: iOS Development, Swift, Mobile Security, Cryptography, FinTech, PCI-DSS, TLS, Secure Enclave, Payment Systems</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30fa89d55a85" width="1" height="1" alt=""><hr><p><a href="https://systemweakness.com/fintech-ios-app-security-a-complete-engineering-guide-from-tls-to-the-secure-enclave-30fa89d55a85">FinTech iOS App Security: A Complete Engineering Guide from TLS to the Secure Enclave</a> was originally published in <a href="https://systemweakness.com/">System Weakness</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Optional: Custom Operators for Safe Unwrapping]]></title>
            <link>https://shoaib-rokon.medium.com/swift-optional-custom-operators-for-safe-unwrapping-c33cbeccfde5?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c33cbeccfde5</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[ios-development]]></category>
            <category><![CDATA[swift-optionals]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 07:48:49 GMT</pubDate>
            <atom:updated>2024-08-01T07:48:49.400Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTaPk61uvsbBbb8lPr-Z6w.jpeg" /></figure><p>In Swift, handling optionals is an essential part of ensuring your code’s safety and reliability. While the ! operator provides a quick way to force-unwrap optionals, it often leads to runtime crashes without much information on what went wrong. This lack of detail can be frustrating when debugging, especially if the crash occurs in a production environment. In this post, we’ll explore some custom operators to improve the clarity and safety of unwrapping optionals in Swift.</p><h4>Introducing the !! Operator</h4><p>To enhance error reporting, we can define a custom operator !!. This operator not only force-unwraps the optional but also allows us to provide a descriptive error message that gets logged if the unwrapping fails.</p><pre>infix operator !!<br><br>func !! &lt;T&gt;(wrapped: T?, errorMessage: @autoclosure () -&gt; String) -&gt; T {<br> if let x = wrapped { return x }<br> fatalError(errorMessage())<br>}</pre><p>Using !!, you can include a custom error message, providing valuable context when a crash occurs. For example:</p><pre>let s = &quot;hello&quot;<br>let i = Int(s) !! &quot;Expected an integer, \&quot;\(s)\&quot; can not be unwrapped&quot;</pre><p>In this case, if the conversion fails, the error message will indicate that the string “hello” could not be converted to an integer, making debugging easier.</p><h4>Asserting in Debug Builds with the !? Operator</h4><p>While crashing with detailed error messages is useful during development, it’s often too severe for production. In production builds, we might prefer to handle unexpected nil values gracefully. The !? operator allows us to assert during debugging and substitute a default value in production.</p><pre>infix operator !?<br><br>func !?&lt;T: ExpressibleByIntegerLiteral&gt;(wrapped: T?, errorMessage: @autoclosure () -&gt; String) -&gt; T {<br>    assert(wrapped != nil, errorMessage())<br>    return wrapped ?? 0<br>}<br><br>func !?&lt;T: ExpressibleByArrayLiteral&gt;(wrapped: T?, errorMessage: @autoclosure () -&gt; String) -&gt; T {<br>    assert(wrapped != nil, errorMessage())<br>    return wrapped ?? []<br>}<br><br>func !?&lt;T: ExpressibleByStringLiteral&gt;(wrapped: T?, errorMessage: @autoclosure () -&gt; String) -&gt; T {<br>    assert(wrapped != nil, errorMessage())<br>    return wrapped ?? &quot;&quot;<br>}</pre><p>With !?, you can provide default values for different types. For instance:</p><pre>let s = &quot;99&quot;<br>let i = Int(s) !? &quot;Expecting an integer, \&quot;\(s)\&quot; can not be unwrapped.&quot;</pre><p>In debug builds, this will assert if the conversion fails. In release builds it will return 0 instead of crashing.</p><blockquote>There are three ways to halt execution. The first is fatalError, which takes a message and stops execution unconditionally. The second is assert, which checks a condition and a message; it stops execution if the condition evaluates to false. However, in release builds, assert statements are removed, so the condition isn’t checked, and execution isn’t halted. The third is precondition, which has the same interface as assert but is not removed in release builds, so if the condition evaluates to false, execution is stopped.</blockquote><h4>Custom Default Values</h4><p>Sometimes, the default values provided by the type aren’t sufficient. In such cases, we can define a version of !? that accepts a pair: a default value and an error message.</p><pre>func !?&lt;T&gt;(wrapped: T?, optionalHandler: @autoclosure () -&gt; (value: T, text: String)) -&gt; T {<br>    assert(wrapped != nil, optionalHandler().text)<br>    return wrapped ?? optionalHandler().value<br>}</pre><p>For example:</p><pre>Int(s) !? (5, &quot;Expected an integer value&quot;)</pre><p>In debug builds, it asserts, if s can’t be converted to an integer. In the release builds, it defaults to 5.</p><h4>Handling Void Optionals</h4><p>The !? operator can also be adapted for optionally chained method calls, which return Void?:</p><pre>func !?(wrapped: ()?, errorMessage: @autoclosure () -&gt; String) {<br>    assert(wrapped != nil, errorMessage())<br>}</pre><p>This is useful when you expect a method chain to execute and don’t want to silently fail if an optional chain breaks:</p><pre>var output: String? = nil<br>output?.write(&quot;something&quot;) !? &quot;Wasn&#39;t expecting chained nil here&quot;</pre><h4>Conclusion</h4><p>These custom operators provide more control over optional unwrapping in Swift. By using !! and !?, you can improve error handling during development and provide safer defaults in production. Remember, while these tools can be helpful, they should be used judiciously. Over-reliance on force-unwrapping, even with better error messages, can still lead to crashes. Always consider safer alternatives like optional binding (if let) and nil-coalescing (??).</p><p>Incorporate these operators into your codebase to make your Swift applications more robust and your debugging process more informative. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c33cbeccfde5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debouncing and Throttling in Swift: A Journey of Refinement]]></title>
            <link>https://shoaib-rokon.medium.com/debouncing-and-throttling-in-swift-a-journey-of-refinement-c5d8ef3613d6?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c5d8ef3613d6</guid>
            <category><![CDATA[property-wrapper]]></category>
            <category><![CDATA[debounce]]></category>
            <category><![CDATA[throttle]]></category>
            <category><![CDATA[swiftui]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Thu, 01 Aug 2024 05:20:02 GMT</pubDate>
            <atom:updated>2024-08-03T10:42:16.241Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*feq_sdit1LeZ9G_rWPf2Xg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@mphotographym?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Moritz Mentges</a> on <a href="https://unsplash.com/photos/selective-focus-photo-of-gear-shift-lever-cj2I_KczBvY?utm_content=creditShareLink&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></figcaption></figure><p>In the world of mobile app development, handling user input efficiently is crucial for delivering a smooth user experience. One common technique is to use debouncing or throttling to manage rapid changes in input, ensuring that our app doesn’t respond too frequently and unnecessarily. In this blog post, I’ll take you through a journey of improving a Swift implementation of debouncing, showcasing how I evolved the code to be more flexible and reusable with each iteration.</p><h4>Initial Implementation: Basic Debouncing</h4><p>The journey began with a straightforward implementation using the Combine framework. I created a class called DebouncedState that conformed to the ObservableObject protocol. This class had two @Published properties: currentValue and debouncedValue. The idea was simple: whenever currentValue changed, the Combine debounce operator would delay updating debouncedValue by a specified duration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef04ab825a8080b5a37ee626f38e2cda/href">https://medium.com/media/ef04ab825a8080b5a37ee626f38e2cda/href</a></iframe><p>The below snippet is an example of how we can use debounce seamlessly in SwiftUI.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb00b795f3f80bc91bf87a43ecfcd1f5/href">https://medium.com/media/fb00b795f3f80bc91bf87a43ecfcd1f5/href</a></iframe><p>This basic implementation effectively managed string inputs but was limited in scope. It was designed specifically for strings, which meant it couldn’t easily be applied to other data types.</p><h4>Generalizing with Generics</h4><p>To extend the functionality beyond strings, the next iteration introduced generics. The DebouncedState class was updated to handle any data type, making it much more versatile.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec9dc8318a024590ce12e975347bb228/href">https://medium.com/media/ec9dc8318a024590ce12e975347bb228/href</a></iframe><p>This change allowed the class to debounce changes for any type of data, making it more adaptable for different use cases. However, while the functionality expanded, the implementation still felt a bit rigid.</p><h4><strong>Refining with Property Wrappers</strong></h4><p>The next significant improvement involved transforming DebouncedState into a property wrapper. This made the debouncing logic more seamless to integrate into SwiftUI views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e33252c79abab62b8ee3fc889227dc1/href">https://medium.com/media/5e33252c79abab62b8ee3fc889227dc1/href</a></iframe><p>Now we have a reusable DebounceState Property Wrapper just like SwiftUI’s State Property Wrapper.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b9b0f835d3c62ea816c8d6c76ae21b3/href">https://medium.com/media/9b9b0f835d3c62ea816c8d6c76ae21b3/href</a></iframe><p>This version encapsulated the state management and operating logic within a property wrapper, making it easier to use in SwiftUI. The property wrapper DebouncedState conformed to DynamicProperty, ensuring it could respond to changes and be used within the SwiftUI framework.</p><p>If we want to use throttle instead of debounce we have to create ThrottleState and it is a lot of repeating ourselves in a world where don’t repeat yourself is the King.</p><h4>Adding Flexibility with Operators</h4><p>The final iteration aimed to provide even more flexibility by allowing different operating strategies, such as debouncing and throttling. To achieve this, I introduced a Operator protocol and corresponding operators for debouncing and throttling.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/679ac6cbfb7792dd5db3bd8f24fa99db/href">https://medium.com/media/679ac6cbfb7792dd5db3bd8f24fa99db/href</a></iframe><p>To further refine the code, it would be beneficial to use the dot prefix style for static member lookups in generic contexts, which was introduced in Swift 5.5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4f81f79739ead098105a771d772a246/href">https://medium.com/media/a4f81f79739ead098105a771d772a246/href</a></iframe><p>This approach offered unparalleled flexibility, allowing users to choose between different state operating strategies like debouncing and throttling with ease. The property wrapper OperatorState could now encapsulate various operating logic, adapting to different scenarios as needed.</p><p>To test the OperatorState property wrapper with the DebounceOperator, you can use XCTest to create unit tests that verify the behavior of debouncing. Here’s an example of how you might write these tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c3c41f2c9dc5cb90165fe6cef7c2808/href">https://medium.com/media/0c3c41f2c9dc5cb90165fe6cef7c2808/href</a></iframe><p>Here is the link to the completed project.</p><p><a href="https://github.com/rokon-uddin/DebounceExample">GitHub - rokon-uddin/DebounceExample</a></p><h4>Conclusion</h4><p>Through these iterations, the initial simple debouncing implementation evolved into a highly flexible and reusable solution. The final implementation leverages Swift’s powerful property wrappers and Combine framework, allowing developers to easily integrate and switch between different state operating strategies.</p><p>Thank you all for your attention 🙏🏻. Feel free to <a href="https://x.com/RokonMohammed">X</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c5d8ef3613d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OperationQueue: Asynchronous Data Provider for list view]]></title>
            <link>https://medium.com/monstar-lab-bangladesh-engineering/operationqueue-asynchronous-data-provider-for-list-view-ee5327ff2647?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/ee5327ff2647</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[concurrency]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 04:58:31 GMT</pubDate>
            <atom:updated>2024-08-01T04:51:55.533Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Il9Ky0OcbLl-lnzzrbq5oA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@gcsgpp">Gabriel Gusmao</a> on <a href="https://unsplash.com/photos/pMmw3ynuXHw">Unsplash</a></figcaption></figure><p>In <a href="https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a"><em>iOS TableView Prefetching DataSource using Swift</em></a><em>, </em>I talked about the prefetching API introduced<em> </em>in iOS 10. To achieve a seamless user experience, prefetching API does an excellent job. But at times we need more than prefetching datasource. One of those times is when the data we want to fetch are from multiple synchronous slow-running tasks depending on one another. Considering such cases, in this article, I explained how to group multiple heavy tasks (both sync and async) using Swift’s powerful multithreading API Operation and I called it an <strong>Asynchronous Data Provider.</strong></p><h4><strong>Prerequisite</strong></h4><p>As you are reading this article, I am hoping that you already know about GrandCentralDispatch (GCD), OpertionQueue and PrefetchingDataSource .</p><h4>Getting Started</h4><p>The sample project of this article populates a table view of filtered images. These images are the results of four heavy loading tasks, both synchronous and asynchronous. I made each task as a subclass of Operation to run these tasks in a OperationGroup and assign one as a dependency of another task.</p><h4>DataLoadOperation:</h4><p>This is the first of four tasks used to fetch images. It downloads the metadata for each image from the internet. Here we used NetworkSimulator to mimic the delay due to network call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce4b9f60a59bf5dfc2fbbab4b47e3d3f/href">https://medium.com/media/ce4b9f60a59bf5dfc2fbbab4b47e3d3f/href</a></iframe><h4>ImageDecompressionOperation:</h4><p>As the name says, this decompresses the compressed data downloaded in DataLoadOperation to UIImage</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b30ab5619988076d16b6d246ea1d622e/href">https://medium.com/media/b30ab5619988076d16b6d246ea1d622e/href</a></iframe><h4><strong>TiltShiftOperation:</strong></h4><p>The responsibility of this class is to apply a gradient with a corner radius to the UIImage passed from ImageDecompressionOperation</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6eb2a8f049831a9bc0054438b09c3db9/href">https://medium.com/media/6eb2a8f049831a9bc0054438b09c3db9/href</a></iframe><h4><strong>ImageFilterOutputOperation:</strong></h4><p>This calls the completion block to return the final output.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1bbd8136ea835c2f5cd914c20088a957/href">https://medium.com/media/1bbd8136ea835c2f5cd914c20088a957/href</a></iframe><h4><strong>TiltShiftImageProvider:</strong></h4><p>This is where all the magic happens. TiltShiftImageProvider. It initializes all tasks, assigns the dependencies to one other accordingly, and in the end adds this array of tasks to OperationQueue. TiltShiftImageProvider just has a single method cancel() which is called whenever we want OperationQueue to stop any ongoing task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9e01347f3aa3ef0d59eb6d21cc8d380/href">https://medium.com/media/c9e01347f3aa3ef0d59eb6d21cc8d380/href</a></iframe><h4><strong>TiltShiftTableViewController:</strong></h4><p>Inside tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) a new imageProvider is initialized and stored in a dictionary. tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) method calls configureCell(_ cell: ImageTableViewCell, at indexPath: IndexPath) to update UI If there is an image available an indexPath or else a new imageProvider has been created and update the cell as soon as the image has been returned from the completion block and finally imageProvider has been stored in the dictionary. In tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) and tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) methods we called cancel() method of each stored imageProvider to stop any ongoing task and then imageProvider has been removed from the dictionary to free up the resources.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c259be5c40f9caa574a29fc6caf737f0/href">https://medium.com/media/c259be5c40f9caa574a29fc6caf737f0/href</a></iframe><h3>Conclusion</h3><p>Operations in Swift are a very powerful way to segregate tasks into multiple classes. As OperationQueue the class is key-value coding (KVC) and key-value observing (KVO) compliant, it keeps track of the progress and dependencies of each task. The below code repo is a perfect example of how to leverage the power of OperationQueue and design an Asynchronous Data Provider.</p><p><a href="https://github.com/rokonuddin/AsyncDataProvider">rokonuddin/AsyncDataProvider</a></p><p>Thank you all for your attention 🙏🏻. feel free to <a href="https://twitter.com/RokonMohammed">tweet</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><p>Check out other articles from our engineering team:<br><a href="https://medium.com/monstar-lab-bangladesh-engineering">https://medium.com/monstar-lab-bangladesh-engineering</a></p><p>Visit our website to learn more about us:<br><a href="http://www.monstar-lab.co.bd/">www.monstar-lab.co.bd</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ee5327ff2647" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monstar-lab-bangladesh-engineering/operationqueue-asynchronous-data-provider-for-list-view-ee5327ff2647">OperationQueue: Asynchronous Data Provider for list view</a> was originally published in <a href="https://medium.com/monstar-lab-bangladesh-engineering">Monstar Lab Bangladesh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Step into Swift Combine]]></title>
            <link>https://medium.com/monstar-lab-bangladesh-engineering/step-into-swift-combine-c0c6daaa3f6e?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c0c6daaa3f6e</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[combine]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[swiftui]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Tue, 27 Aug 2019 15:00:24 GMT</pubDate>
            <atom:updated>2019-08-28T08:28:49.301Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ATQhNcG74FbCEL_0TifXQQ.png" /><figcaption>WWDC 2019</figcaption></figure><h3><strong>What is Combine?</strong></h3><blockquote>A unified declarative API for processing values over time.</blockquote><blockquote>Often in our code, we have many places where we have some sort of value or event Publisher and some Subscriber is interested in receiving values from that Publisher. And some interested party comes along and establishes a connection between these Publisher and Subscriber. Once the connection is established, the Subscriber sometimes declares that they are interested in receiving values from that Publisher (upstream), after which the Publisher is free to begin sending values to Subscriber (downstream). This goes on until either the Publisher decides to stop sending values, whether because it finished or there was some sort of failure, or by someone choosing to cancel the subscription. This general shape of communication appears throughout our software, whether it’s callbacks or closures or any other situations where there’s asynchronous communication. — <a href="https://developer.apple.com/videos/play/wwdc2019/721/">Combine in Practice, WWDC 2019</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tRSjCaMFVfyBabMxSnZj7A.png" /><figcaption>This is the Pattern that Combine is all about, WWDC 2019</figcaption></figure><h3>Key Concepts</h3><p>Combine has following three concepts: Publishers, Subscribers, and Operators .</p><h4>Publishers</h4><p>Publishers are the declarative part of Combine’s API which describe how values and errors are produced and allow registration of a Subscriber to receive these values over time. They specify two associatedTypes and a key function as shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yhhLU-3nOgAD2uqg2JRMGw.png" /><figcaption>Publisher protocol. WWDC 2019</figcaption></figure><ul><li>Output is the type of value Publisher it produces.</li><li>Failure is the kind of errors that Publisher produces. If Publisher does not produce an error, then we can use type never for that associated type.</li><li>subscribe&lt;S: Subscriber&gt;(_ subscriber: S) is the key function that describes how to attach a Subscriber to a Publisher with the generic constraints that the associated types must match the Subscriber’s Input to Publisher’s Output, and the Subscriber’s Failure to Publisher’s Failure.</li></ul><p>Here are some additional convenience publishers:</p><p><strong>Just:</strong> It provides a single result and then terminates, it takes a failure type of &lt;Never&gt;</p><p><strong>Future:</strong> A future is initialized with a closure that eventually resolves to a single output value or failure completion.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2ea3176f1b45fb377eeee6ed7d08242c/href">https://medium.com/media/2ea3176f1b45fb377eeee6ed7d08242c/href</a></iframe><p><strong>Published:</strong> A property wrapper adds a Combine publisher to any property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/810b2f6c69a60bd6c76a214ef9cba461/href">https://medium.com/media/810b2f6c69a60bd6c76a214ef9cba461/href</a></iframe><p>Published wraps the variable, address, and will trigger events whenever the variable is mutated. Any subscriber(s) subscribing to the property will also receive any initial value being set upon the property’s initialization.</p><p>The below example is the implementation of Publisher protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3527c0590cb4241504ce2d40a1541208/href">https://medium.com/media/3527c0590cb4241504ce2d40a1541208/href</a></iframe><h4>Subscribers</h4><p>Subscribers are the counterparts of Publishers. They receive values, including the completion if the Publisher is finite. As Subscribers usually act and mutate state upon receipt of values, so they are reference types in Swift; in other word, they are classes. Below is the protocol of Subscriber:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6tsL2jqgJpfvW4NaU3rcg.png" /><figcaption>Subscriber protocol. WWDC 2019</figcaption></figure><p>Subscriber has two associatedTypes as shown above. One is Input and the other is Failure. Subscriber has three well-defined event functions to receive a subscription, values and a completion as described below:</p><ol><li>A Publisher will call receive(subscription: Subscription) just once in response to a subscribe call.</li><li>A Publisher can then call receive(_ input: Input) to provide values to the Subscriber.</li><li>Once the Publisher has finished or a failure has occurred it sends <strong>at most</strong> a completion signal and no further values are emitted by a Publisher once that completion has been signalled.</li></ol><p>There are two special Subscribers that takes burden from us:</p><ul><li>sink(receiveCompletion:receiveValue:): Sink takes two closures. receiveCompletion executes upon subscribers completion and it is an enum that indicates whether the publisher finished normally or failed with an error and receiveValue triggers every time it receives an element from subscribed publisher.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/050a7cf59c98f09cc0bc1ad993a6d22f/href">https://medium.com/media/050a7cf59c98f09cc0bc1ad993a6d22f/href</a></iframe><ul><li>assign(to:on:): It immediately assigns every element it receives to a property of a given object using key path to indicate the property</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ac78d1bbffaaab2b7313682e5399c5ae/href">https://medium.com/media/ac78d1bbffaaab2b7313682e5399c5ae/href</a></iframe><h4>Operator</h4><p>While working with Combine we often come to a scenario where output of the Publisher does not match the input of the Subscriber. Operators are the real saviors for such cases. They subscribe to Publishers (upstream), describe a behavior for changing values and then send the result to a Subscriber (downstream). Based on actions, Operators can be divided into the three following types:</p><p><strong>1. Transformation Operators:</strong></p><ul><li>map: it operates just like Swift standard library map, except it operates on Publishers.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*yPWzI3xeKo6IB-n41vE85A.png" /><figcaption>Marble diagram of map</figcaption></figure><ul><li>flatMap: it tears down an observable sequence where elements of the observable itself are observables and merges the resulting observable sequences into one observable sequence. flatMap is mostly used in error handling scenarios.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/690/1*umtbqp-eOnngqpFQ5R7nTw.png" /><figcaption>Marble diagram of flatMap</figcaption></figure><p><strong>2. Combination Operators:</strong></p><ul><li>merge: it combines multiple Observables into one by merging their elements</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*n-XwWpr2-y1XCxiGjBHCpw.png" /><figcaption>Marble diagram of merge</figcaption></figure><ul><li>combineLatest: it combines the latest elements from two or more Publishers when any one of the Publishers emits an element.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TEQirIbcm28KIBRj28ymgw.png" /><figcaption>Marble diagram of combineLatest</figcaption></figure><ul><li>zip: this is similar to Combine Latest but unlike Combine Latest Zip waits for each Publisher to emit new elements.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*UPSGh_eE1ab4_CBGNOdxuA.png" /><figcaption>Marble diagram of zip</figcaption></figure><p><strong>3. Filtering and other Operators:</strong></p><p>There are a lot more operators like filter removeDuplicates, debounce, count, contains and more which are self explanatory. I encourage you to go to <a href="https://developer.apple.com/documentation/combine/publisher">Apple’s documentation</a> and try some yourself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*loGk2eS7bPHqSa26Wt2JVQ.png" /><figcaption>Lot more Operators, WWDC 2019</figcaption></figure><h4><strong>Subject</strong></h4><p>Subjects are special types of Publisher in Combine in which we can subscribe as well as send events to them dynamically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8wCDPII4uPdX2qdEZEBh0A.png" /><figcaption>Subject Protocol, WWDC 2019</figcaption></figure><p>As shown in the above image, Subject describes two functions. One is to send value and other is to send completion with failure.</p><p>Combine provides two very handy subjects:</p><ul><li><strong>PassthroughSubject: </strong>It sends every element after subscription<strong>.</strong></li><li><strong>CurrentValueSubject: </strong>It behaves same as the <strong>PassthroughSubject</strong> but unlike <strong>PassthroughSubject, CurrentValueSubject </strong>stores the most recent elements and send to new subscribers.</li></ul><h4>Scheduler</h4><ul><li>receive: it takes a single required parameter (on:) which accepts a scheduler, and an optional parameter (optional:)</li></ul><pre>examplePublisher<strong>.receive</strong>(on: <strong>RunLoop.</strong>main)</pre><ul><li>subscribe: Subscribe defines the scheduler on which to run a publisher in a pipeline.</li></ul><pre>networkDataPublisher     <br><strong>.subscribe</strong>(on: backgroundQueue)  // 1 <br><strong>.receive</strong>(on: <strong>RunLoop.</strong>main)  // 2<br><strong>.assign</strong>(to: \<strong>.</strong>text, on: nameLabel)  // 3</pre><ol><li>The subscribe call requests the publisher (and any pipeline invocations before this in a chain) be invoked on the backgroundQueue.</li><li>The receive call moves the data to the main thread to update the UI elements</li><li>The assign call uses the <a href="https://heckj.github.io/swiftui-notes/#reference-assign">assign</a> subscriber to bind data to a KVO compliant object.</li></ol><h4>AnyCancellable</h4><p>AnyCancellable is used to keep the reference of a subscriber so that we can clean up the subscriber on deallocation.</p><pre>var cancellable: AnyCancellable?</pre><pre>let sinkSubscriber = aPublisher<br>    .sink { data in<br>        print(&quot;received &quot;, data)<br>    }<br>cancellable = AnyCancellable(sinkSubscriber)</pre><h4><strong>Source Code:</strong></h4><p><a href="https://github.com/rokonuddin/CombineBook.git">rokonuddin/CombineBook</a></p><h3>Related Articles:</h3><p><a href="https://heckj.github.io/swiftui-notes/#aboutthisbook">Using Combine</a></p><p><a href="https://medium.com/flawless-app-stories/problem-solving-with-combine-swift-4751885fda77">Problem Solving with Combine Swift</a></p><p><a href="https://www.avanderlee.com/swift/combine/">Getting started with the Combine framework in Swift</a></p><p><a href="https://rxmarbles.com/">RxMarbles</a></p><h3>Conclusion</h3><p>Combine is a very powerful framework, introduced in Swift 5.1. It enables developers to dive into reactive programming. Apple ingeniously designed this language feature which goes hand in hand with Apple’s new declarative UI framework SwiftUI yet keeping UIKit unchanged.</p><p>Though Combine itself is a huge topic to write on, in this article I have provided explanations and covered the basics to start with.</p><p>Later I have tried to cover most commonly used keywords in Combine with diagrams and code snippets.</p><p>Finally, I shared a working example of Combine with SwiftUI.</p><p>I hope that you have enjoyed this article. I encourage you to read my other articles on <a href="https://medium.com/monstar-lab-bangladesh-engineering/swift-from-protocol-to-associatedtype-then-type-erasure-a4093f6a2d08">Swift Type Erasure</a>, <a href="https://medium.com/monstar-lab-bangladesh-engineering/ios-custom-uiview-from-xib-7b02cc05f75c?source=your_stories_page---------------------------">Custom UIView from .xib</a> and <a href="https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a?source=your_stories_page---------------------------">TableView Prefetching DataSource using Swift</a></p><p>Thank you all for your attention 🙏🏻. Feel free to <a href="https://twitter.com/RokonMohammed">tweet</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><p>Visit our website to learn more about us:<br><a href="http://www.monstar-lab.co.bd/">www.monstar-lab.co.bd</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c0c6daaa3f6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monstar-lab-bangladesh-engineering/step-into-swift-combine-c0c6daaa3f6e">Step into Swift Combine</a> was originally published in <a href="https://medium.com/monstar-lab-bangladesh-engineering">Monstar Lab Bangladesh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift: From Protocol to AssociatedType then Type Erasure]]></title>
            <link>https://medium.com/monstar-lab-bangladesh-engineering/swift-from-protocol-to-associatedtype-then-type-erasure-a4093f6a2d08?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4093f6a2d08</guid>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[generic-programming]]></category>
            <category><![CDATA[type-erasure]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Mon, 11 Mar 2019 04:14:03 GMT</pubDate>
            <atom:updated>2019-03-12T04:38:14.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MxVd53sVBuSR83OC7wZteg.png" /><figcaption>Grand Sultan Tea Resort &amp; Golf, Sreemangal, Bangladesh</figcaption></figure><h4>Motivation</h4><p>We use classes to represent a symmetric operation, like Comparison, for example, if we want to write a generalized sort or binary search where we need to compare two elements , we end up this something as below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a9f29317ad26f9772a47dc4e19e162a2/href">https://medium.com/media/a9f29317ad26f9772a47dc4e19e162a2/href</a></iframe><p>We don’t know anything about an arbitrary instance of Ordered yet. So if the method is not implemented by a subclass, well, there is nothing we can do other than trap. Now, this is the first sign that we are fighting the type system. And if we fail to recognize that, it is also where we start lying to ourselves. Because we brush the issue aside, telling ourselves as long as each subclass of Order implements precedes, we will be okay. Making it the subclass’s problem. So we go ahead and implement an example of Ordered as below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ca4c4ebe0fb42b4dfdf1eb5940d18cd/href">https://medium.com/media/7ca4c4ebe0fb42b4dfdf1eb5940d18cd/href</a></iframe><p>It got double value and we override precedes to do the comparison. other is just arbitrary Ordered and not a number. So we don’t know that other has value property. We down-cast Other to Number to get to the right type to compare. It is a static type safety hole. Classes don’t let us express this crucial type relationship between the type of self and type of Other. It is a code smell. So any time we see a force down-cast in our code, it’s a good sign that some important type relationship has been lost, and often that’s due to classes for abstraction. Clearly, what we need is a better abstraction mechanism.</p><h4><strong>Better Abstraction Mechanism</strong></h4><p>A abstraction mechanism must have following properties:</p><ul><li>Doesn’t force to accept implicit sharing or lost type relationships</li><li>Force to choose just one abstraction and do it at the time types are defined</li><li>Doesn’t force to accept unwanted instance data or the associated initialization complexity</li><li>Doesn’t leave ambiguity about what need to override.</li></ul><p>And yes…!!! Protocol has all of these properties.</p><blockquote>Don’t start with a class. Start with a protocol…!!!</blockquote><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fa5auAyjyCOf1S%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fprincess-leia-a5auAyjyCOf1S&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fa5auAyjyCOf1S%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/4017a37805d83c5c293bbcb3fce48e29/href">https://medium.com/media/4017a37805d83c5c293bbcb3fce48e29/href</a></iframe><h4><strong>Protocol-Oriented Programming in Swift</strong></h4><p>When Swift was made, it was made as the first protocol-oriented. Though Swift is great for object-oriented programming, but from the way <em>for-loops</em> and <em>String</em> <em>literals</em> work to the emphasis in the standard library on <em>generics</em>, at its hearts, Swift is protocol-oriented. There is a saying in Swift: “Don&#39;t start with class, start with protocol” . So let’s redo the binary search example with protocol:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b922ad971a49d198f7aab8f91e7f411c/href">https://medium.com/media/b922ad971a49d198f7aab8f91e7f411c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fh2MLtoOjxtkGY%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fimpressed-bfd-h2MLtoOjxtkGY&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fh2MLtoOjxtkGY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="470" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8fb9f782bb56ac4dbff4d05fba1b612/href">https://medium.com/media/b8fb9f782bb56ac4dbff4d05fba1b612/href</a></iframe><h4><strong>Protocol Self Requirement</strong></h4><p>Once we have a Self-requirement to a protocol, it moves the protocol into a very different world, where the capabilities have a lot less overlap with classes.</p><ul><li>It stops being usable as a type</li><li>Collections become homogeneous instead of heterogeneous</li><li>An interaction between instances no longer implies an interaction between all model types.</li><li>We trade dynamic polymorphism for static polymorphism, but, in return for that extra type information we are giving the compiler, it is more optimizable</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZrkGRZIzWYDHSzAXClZIpQ.png" /><figcaption>Protocol Oriented Programming in Swift, session 408, #WWDC2015</figcaption></figure><h4><strong>Protocol Extension</strong></h4><p>In our current implementation, we need to implement precedes method for each type. e.g:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ae36ca1ce430fa227f79d3369e834cd/href">https://medium.com/media/8ae36ca1ce430fa227f79d3369e834cd/href</a></iframe><p>Here comes the power of protocol. One implementation to rule them all by using a constrained extension on Ordered.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/183a72de099a9264941fb38a38fb6f20/href">https://medium.com/media/183a72de099a9264941fb38a38fb6f20/href</a></iframe><p>Let’s take constrained extension a step further</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18446782e0a3ce24c2cc2bc6130c78b3/href">https://medium.com/media/18446782e0a3ce24c2cc2bc6130c78b3/href</a></iframe><h4>Protocol Associated Types:</h4><p>By now we know what is Protocol Oriented Programming (POP). But POP without Protocol Associated Types (PAT) will never be completed.</p><p>associatedtype is a protocol generic placeholder for an unknown Concrete Type that requires concretisation on adoption at <strong>Compile</strong> time.</p><blockquote>Protocol Associated Types (PAT)= Type Alias + Generics</blockquote><p>At one stage of programming in Swift, many of us came across below error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y5nt6j9YwOC0d4r5sgTxlg.png" /><figcaption>Error while trying to use Generic in Protocol</figcaption></figure><p>Swift does not allow us to use Generic parameters in Protocol. To bypass this limitation, Swift introduced Protocol Associated Type . Below example shows how to use associatedType in Protocol</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6dc0efe13c34ff6b068765bfe8a4dd/href">https://medium.com/media/1f6dc0efe13c34ff6b068765bfe8a4dd/href</a></iframe><h4>Type Erasure</h4><p>Though associatedType solved one problem but it also introduce another problem. In Swift we can not use Protocol with associatedType as a Type. What it means is, if we set a variable type to ViewModelType, Swift compiler will show following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HHSawDv_hlarfjVBPW1BfQ.png" /><figcaption>Error while using Protocol with AssociatedType as Type</figcaption></figure><p>Type Erasure is the only saviour here to this error. There are three patterns that we can apply to solve the problem of generic constraints requirement.</p><ul><li>Constrained Type Erasure: erases a type but keeps a constrain on it.</li><li>Unconstrained Type Erasure: erases a type without a constrain on it</li><li>Shadow Type Erasure: erases a type by camouflaging the type</li></ul><h4>Example</h4><p>The below code snippet shows how to implement multi-sectioned heterogeneous TableViewCell using Unconstrained Type Erasure</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40f9c05ea3b5dbe6d65c2224a7a069c6/href">https://medium.com/media/40f9c05ea3b5dbe6d65c2224a7a069c6/href</a></iframe><p>If you download the project shared below and run the app, you will see the app has two models TextCellModel and ImageCellModel displayed using two table cells TextTableViewCell and ImageTableViewCell respectively. As the app has different models and cells under single TableView section, without TypeErasure we would face following problems</p><ul><li>Self or Associated Type Requirement:</li></ul><pre>let items: [CellModel] = [a_text_model, a_image_mode] // Error explained above</pre><p>CellModel has associated type requirement to avoid spaghetti code while dequeueing TableCell. Without associated type requirement out code would be as:</p><pre>func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -&gt; UITableViewCell {<br>   let items = sections[indexPath.section].items<br>   let item = items[indexPath.row]</pre><pre>   // More the model types, more the if-else<br>   if item is TextCellModel {<br>    // load TextTableViewCell<br>   } else {<br>    // load ImageTableViewCell<br>   }<br>}</pre><ul><li>Heterogeneous Array:</li></ul><p>As TableView has different models and cells under same section, without TypeErasure we had to populate different array for different model which will lead to lots of if-else. Instead we used as:</p><pre>let imageCell = AnyCell(ImageCellModel(&quot;cyclamen&quot;))<br>let quoteCell = AnyCell(TextCellModel(&quot;Hello World.&quot;, author: &quot;-&quot;))<br>let anyCells = [imageCell, quoteCell]</pre><p>if we had just directly instantiated our ImageCellModel instance using the ImageCellModel initializer, it would be of type ImageCellModel. But because we have instantiated using this AnyCell wrapper class, ImageCellModel is now instantiated as type AnyCell . We have just erased type information (<em>this is what type erasure means</em>)</p><p>Wrapper classes are conventionally prefixed with the word “Any”, in order to guarantee that you will instantiate an object that implements our protocol and fills the generic type, without necessarily having the implementation on hand.</p><p>🎉 Using AnyCell wrapper we’ve erased the Type requirement when conforming to CellModel protocol. The init function is without clause and we now have a heterogenous collection Type and dynamic dispatch at our disposition. 👍🏿</p><h4>Source Code:</h4><p><a href="https://github.com/rokonuddin/TypeErasure">rokonuddin/TypeErasure</a></p><h4>Related Articles:</h4><p><a href="https://medium.com/dunnhumby-data-science-engineering/swift-associated-type-design-patterns-6c56c5b0a73a">Swift Associated Type Design Patterns</a></p><p><a href="https://developer.apple.com/videos/play/wwdc2015/408/">Protocol-Oriented Programming in Swift</a></p><p><a href="https://www.natashatherobot.com/swift-type-erasure/">Swift: Attempting to Understand Type Erasure</a></p><p><a href="https://academy.realm.io/posts/tryswift-gwendolyn-weston-type-erasure/">Keep Calm and Type Erase On</a></p><h4>Conclusion</h4><p>We often end up writing spaghetti code while implementing TableView or CollectionView with different types of cells and models. TypeErasure is the right choice to avoid spaghetti code, makes code much more organized and increase readability. I hope that you have enjoyed this article. I encourage you to read my other articles <a href="https://medium.com/monstar-lab-bangladesh-engineering/ios-custom-uiview-from-xib-7b02cc05f75c?source=your_stories_page---------------------------">Custom UIView from .xib</a> and <a href="https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a?source=your_stories_page---------------------------">TableView Prefetching DataSource using Swift</a></p><p>Thank you all for your attention 🙏🏻. feel free to <a href="https://twitter.com/RokonMohammed">tweet</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><blockquote><strong>Disclaimer</strong>: I went through bunch of other <em>articles and </em>copied easy to understand examples and sentences while writing this article</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4093f6a2d08" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monstar-lab-bangladesh-engineering/swift-from-protocol-to-associatedtype-then-type-erasure-a4093f6a2d08">Swift: From Protocol to AssociatedType then Type Erasure</a> was originally published in <a href="https://medium.com/monstar-lab-bangladesh-engineering">Monstar Lab Bangladesh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS Custom UIView from .xib]]></title>
            <link>https://medium.com/monstar-lab-bangladesh-engineering/ios-custom-uiview-from-xib-7b02cc05f75c?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b02cc05f75c</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uikit]]></category>
            <category><![CDATA[objective-c]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Sat, 22 Dec 2018 15:41:48 GMT</pubDate>
            <atom:updated>2018-12-26T02:31:04.306Z</atom:updated>
            <content:encoded><![CDATA[<h3>iOS Custom UIView from .xib</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IiW_LejBWton4yMvjZx2ig.png" /><figcaption>A beautiful view</figcaption></figure><p>In iOS App development, creating custom views is a very common practice. We often create custom views for reusability, to segregate responsibility or to decouple dependencies etc. Though there are tons of stackoverflow answers, medium, blogs etc. on this topic, yet it is very tough to find a neat and comprehensive example of creating custom view from .xib.</p><p><strong>Let’s begin with following steps:</strong></p><p><strong>Step 1</strong></p><p>Create a single view app project</p><p><strong>Setp 2</strong></p><p>Add a .xib file as shown in below image and name it “CustomView”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3Z6Sdz0zcCAI2kNeT8ILw.png" /><figcaption>Creating CustomView.xib file</figcaption></figure><p><strong>Step 3</strong></p><p>Just like previous step add CustomView class. This time select CocoaTouch file and choose UIView in subclassof section and also name it “CustomView”</p><p><strong>Step 4</strong></p><p>Select the CustomView.xib file and from Xcode’s Attribute inspectors set file owner of CustomView.xib to CustomView class as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LlrIAsrXpQPHPXdPbBjjXQ.png" /><figcaption>Setting view’s file owner</figcaption></figure><p>Now, here comes so many questions like: What is file owner? or Why not setting subclass instead of fileowner? etc.</p><p>Few points to be remembered:</p><ul><li>The fileowner is the object that loads the nib, i.e. fileowner receives the message loadNibName: or initWithNibName: .<br>If we want to access any objects in the nib after loading it, you can set an outlet in the file owner. ViewController acts as fileowner for View in storyboard that is why we don’t explicitly set fileowner for view in storyboard.</li><li>The reason it is called file owner and given a special place, is because unlike the other objects in the nib, the file owner is external to the nib and is not part of nib. In fact, it only becomes available when the nib is loaded. So the file owner is a stand-in or proxy for the actual object which will later load the nib.</li><li>So you created a fancy view with lots of subviews eg: buttons, labels, etc . If you want to modify any of these subviews any time after loading the nib, we set outlets for these objects to the fileowner.</li><li>Whenever we create custom view from xib we set its fileowner not custom sub class.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q6WN6t39Pl4zXTfpxoczag.png" /><figcaption>Drawing outlet from a view to its file owner</figcaption></figure><p>If we now select Assistant editor in Xcode, it will show corresponding class CustomView for the selected .xib as show below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Fr0B53c87fnRCEqxca6GA.png" /><figcaption>.xib and it’s corresponding class `CustomView`</figcaption></figure><p><strong>Step 5</strong></p><p>Add following code toCustomView class</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0417c76980202a1a36ff3e07f3af7672/href">https://medium.com/media/0417c76980202a1a36ff3e07f3af7672/href</a></iframe><p>Add a button to CustomView by dragging from object library and draw the outlet and action as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cRR8ckvskRX2qXvrptwzgw.png" /><figcaption>Drawing acting for button</figcaption></figure><p>There are two place where we set fileowner</p><ol><li>In the .xib file as shown in <strong>Step 4</strong>. We do it so that we can draw outlet and action. Without setting fileowner Xcode would not able to connects the outlets and actions</li><li>Programmatically in fromNib method as shown below as loadNibName method takes fileowner as parameter. If we send nil instead of self it will overwrite previously assign fileowner to nill .</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/500a1c0b658c2d2252856d32095cf5d0/href">https://medium.com/media/500a1c0b658c2d2252856d32095cf5d0/href</a></iframe><p><strong>Step 6</strong></p><p>CustomView is now fully baked. It is time to serve it. There are two ways we can add the CustomView</p><ol><li>By setting subclass of view in storyboard. In this case init?(coder aDecoder: NSCoder) gets called even though we did not call the method. Because in stoaryboard interface builder serializes the state of that object on to disk, then deserialize it when the storyboard appears on screen. After setting subclass we can draw outlet of custom view of type CustomView</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kFRcxx-gYtEYYlAwjOlk9g.png" /><figcaption>Setting custom view as subclass from storyboard</figcaption></figure><p>Add bellow code to your view controller</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f6739ec3d59fd8eef831ac1b063d2ee/href">https://medium.com/media/1f6739ec3d59fd8eef831ac1b063d2ee/href</a></iframe><p>2. The second way we can use CustomView is programmatically as shown below. This time init(frame: CGRect) get called instead of init?(coder aDecoder: NSCoder) as we called the init(frame: CGRect) method explicitly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/399c0e6ec4768cb16ce63b49d6aab838/href">https://medium.com/media/399c0e6ec4768cb16ce63b49d6aab838/href</a></iframe><p><strong>Demo</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*pcdu1848Bw0H0KZIcRqEMQ.gif" /><figcaption>Demo of Custom View</figcaption></figure><p><strong>Conclusion</strong></p><p>That’s all about creating custom view from .xib. If you enjoy this tutorial, I highly recommend you to read my another post on <a href="https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a">table view prefetching</a>.</p><p>Enough of talking. Let the code talk now:</p><p><a href="https://github.com/rokonuddin/CustomView">rokonuddin/CustomView</a></p><p>Thank you all for your attention 🙏🏻. feel free to <a href="https://twitter.com/RokonMohammed">tweet</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b02cc05f75c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monstar-lab-bangladesh-engineering/ios-custom-uiview-from-xib-7b02cc05f75c">iOS Custom UIView from .xib</a> was originally published in <a href="https://medium.com/monstar-lab-bangladesh-engineering">Monstar Lab Bangladesh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[iOS TableView Prefetching DataSource using Swift]]></title>
            <link>https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a?source=rss-60a50a77a83c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3de593530c4a</guid>
            <category><![CDATA[uitableview]]></category>
            <category><![CDATA[objective-c]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[uicollectionview]]></category>
            <dc:creator><![CDATA[Mohammed Rokon Uddin]]></dc:creator>
            <pubDate>Wed, 12 Dec 2018 03:58:21 GMT</pubDate>
            <atom:updated>2018-12-22T15:27:19.034Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*Lvq8VnVEpNYEBll9OhD21g.png" /></figure><p>Apple has introduced API for prefetching <em>UITableView</em> and <em>UICollectionView</em> in iOS 10. This is a short story of how to implement <em>UITableViewDataSourcePrefetching</em> protocol.</p><h4><strong>Overview</strong></h4><p>To implement prefetching, we confirmed <em>UITableViewDataSourcePrefetching</em> protocol to our view controller just like <em>UITableViewDataSource</em> and <em>UITableViewDelegate</em>. That enables table view’s data source to begin loading data for cells before <em>tableView(_:cellForRowAt:)</em> data source method is called.</p><p><strong>Getting Started</strong></p><p>Set view controller to table view prefetch datasource</p><pre>tableView.prefetchDataSource = self</pre><p>Initiate asynchronous loading of the data required for the cells at the specified index paths in your implementation of <em>tableView(_:prefetchRowsAt:)</em></p><pre>func tableView(_ tableView: UITableView, prefetchRowsAt indexPaths: [IndexPath]) {<br>    for indexPath in indexPaths {<br>     guard let _ = loadingOperations[indexPath] else { return }<br>      if let dataLoader = dataStore.loadPhoto(at: indexPath.row) {<br>         loadingQueue.addOperation(dataLoader)<br>         loadingOperations[indexPath] = dataLoader<br>      }<br>    }<br>}</pre><p>Cancel pending data load operations when the table view informs you that the data is no longer required in the <em>tableView(_:cancelPrefetchingForRowsAt:)</em> method</p><pre>func tableView(_ tableView: UITableView, cancelPrefetchingForRowsAt indexPaths: [IndexPath]) {<br>   for indexPath in indexPaths {<br>     if let dataLoader = loadingOperations[indexPath] {<br>        dataLoader.cancel()<br>        loadingOperations.removeValue(forKey: indexPath)<br>     }<br>   }<br>}</pre><p><strong>Loading Data Asynchronously</strong></p><p>Unlike <em>tableView(_:cellForRowAt:)</em>, the <em>tableView(_:prefetchRowsAt:)</em> method is not necessarily called for every cell in the table view. It is called for cells that are not visible in the screen. Implementation of <em>tableView(_:cellForRowAt:) </em>therefore must be able to handle the following potential situations</p><ul><li>Data has been loaded via the prefetch request and is ready to be displayed.</li></ul><pre>...<br>// Has the data already been loaded?<br>if let image = dataLoader.image {<br>    cell.updateAppearanceFor(image)<br>    loadingOperations.removeValue(forKey: indexPath)<br>}<br>...</pre><ul><li>Data is currently being prefetched but is not yet available.</li></ul><pre>...<br>else {<br>   // No data loaded yet, so add the completion closure to update the cell once the data arrives<br>   dataLoader.loadingCompleteHandler = updateCellClosure<br>}<br>...</pre><ul><li>Data has not yet been requested.</li></ul><pre>// Need to create a data loaded for this index path<br>if let dataLoader = dataStore.loadImage(at: indexPath.row) {<br> // Provide the completion closure, and kick off the loading operation<br> dataLoader.loadingCompleteHandler = updateCellClosure<br> loadingQueue.addOperation(dataLoader)<br> loadingOperations[indexPath] = dataLoader<br>}</pre><p>To handle all of these situations Operation is used to load the data for each row. We create the Operation object and store it in the prefetch method. The data source method can then either retrieve the operation and result or create new operation if doesn’t exist.</p><pre>class DataLoadOperation: Operation {<br>    var image: UIImage?<br>    var loadingCompleteHandler: ((UIImage?) -&gt; ())?<br>    private var _image: ImageModel<br>    <br>    init(_ image: ImageModel) {<br>        _image = image<br>    }<br>    <br>    override func main() {<br>        if isCancelled { return }<br>        guard let url = _image.url else { return }<br>        downloadImageFrom(url) { (image) in<br>            DispatchQueue.main.async() { [weak self] in<br>                guard let `self` = self else { return }<br>                if self.isCancelled { return }<br>                self.image = image<br>                self.loadingCompleteHandler?(self.image)<br>            }<br>        }<br>    }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*JlX0LDCr9nZ3Z01vl0ilcw.gif" /><figcaption>Seamless prefetching!</figcaption></figure><h4>Conclusion</h4><p>I hope that you have enjoyed this tutorial and that it helped you understand the how to implement prefetching protocol and your app more user interactive. Tried to be very brief and focused. If you want to know more about Apple prefetching protocol, I encourage you to <a href="https://developer.apple.com/videos/play/wwdc2016/219/">watch Apple’s WWDC session</a> on prefetching protocol.</p><p>Only source code is real:</p><p><a href="https://github.com/rokonuddin/TableViewPrefetch">rokonuddin/TableViewPrefetch</a></p><p>Thank you all for your attention 🙏🏻. feel free to <a href="https://twitter.com/RokonMohammed">tweet</a> and get <a href="https://www.linkedin.com/in/rokonuddin/">connected</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3de593530c4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/monstar-lab-bangladesh-engineering/tableview-prefetching-datasource-3de593530c4a">iOS TableView Prefetching DataSource using Swift</a> was originally published in <a href="https://medium.com/monstar-lab-bangladesh-engineering">Monstar Lab Bangladesh Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>