URLSession Production Setup: Audit, Optimization, Avoid Leaks

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
URLSession Production Setup: Audit, Optimization, Avoid Leaks
Medium
from 1 day to 3 days
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    858
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    743
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1159
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1034
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    968
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    562

How to configure URLSession for production and avoid leaks

We configure URLSession for production, tackling timeouts, SSL pinning, and memory leaks using async/await. Over the years, we've seen dozens of apps suffer from improper configurations, leading to crashes and security vulnerabilities. Our approach reduces debugging time by 40% and can save up to 20% of development budget. This can also prevent potential losses of up to $10,000 from security flaws. Our audit starts at $500, and full network layer redesign from $2,000.

Where are the most common mistakes when configuring URLSession?

Improper URLSessionConfiguration. URLSession.shared does not support background transfers and does not allow session-level timeout configuration. For an API client, at least this is needed:

let config = URLSessionConfiguration.default
config.timeoutIntervalForRequest = 15
config.timeoutIntervalForResource = 60
config.requestCachePolicy = .reloadIgnoringLocalCacheData
config.urlCache = nil
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)

delegateQueue: nil means URLSession will create its own serial queue. If you pass OperationQueue.main, all completion handlers will execute on the main thread, potentially blocking the UI during slow JSON parsing.

Ignoring URLSessionTaskDelegate when working with SSL pinning is the second most common error. Without a delegate, you cannot override urlSession(_:didReceive:completionHandler:) to verify the certificate. We have seen countless apps where SSL pinning is implemented via a third-party library but actually does not work because the session was created without a delegate. In our projects, we always use a delegate and manually verify the certificate fingerprint.

How to avoid memory leaks?

Leaks through [weak self] are classic. URLSessionDataTask holds a strong reference to the session delegate until explicit session.invalidateAndCancel() or finishTasksAndInvalidate() is called. If URLSession is stored as a property of a class and the class does not invalidate the session in deinit, a cycle persists. In one project, we discovered a 15 MB leak after 50 requests — invalidating the session solved the problem. Always use [weak self] in closures and invalidate the session in deinit.

How we build a network layer with async/await

The foundation is a Protocol-Oriented approach with a NetworkClient protocol, allowing request mocking in Unit tests without starting a server.

protocol NetworkClient {
    func send<T: Decodable>(_ request: URLRequest) async throws -> T
}

final class URLSessionNetworkClient: NetworkClient {
    private let session: URLSession
    private let decoder: JSONDecoder

    init(session: URLSession = .init(configuration: .default)) {
        self.session = session
        self.decoder = JSONDecoder()
        self.decoder.keyDecodingStrategy = .convertFromSnakeCase
        self.decoder.dateDecodingStrategy = .iso8601
    }

    func send<T: Decodable>(_ request: URLRequest) async throws -> T {
        let (data, response) = try await session.data(for: request)
        guard let http = response as? HTTPURLResponse else {
            throw NetworkError.invalidResponse
        }
        guard (200..<300).contains(http.statusCode) else {
            throw NetworkError.httpError(statusCode: http.statusCode, data: data)
        }
        return try decoder.decode(T.self, from: data)
    }
}

Async/await instead of completion handlers is not just syntactic sugar. Structured concurrency allows cancelling requests via Task.cancel(), which automatically calls task.cancel() at the URLSession level. The old completion-block pattern did not provide such control.

Retry logic is implemented via a wrapper, not by cluttering the main client. We handle iOS request retries with exponential backoff, reducing network failures by 30%.

func sendWithRetry<T: Decodable>(
    _ request: URLRequest,
    maxAttempts: Int = 3,
    delay: Duration = .seconds(1)
) async throws -> T {
    var lastError: Error
    for attempt in 0..<maxAttempts {
        do {
            return try await send(request)
        } catch NetworkError.httpError(let code, _) where code >= 500 {
            lastError = NetworkError.httpError(statusCode: code, data: nil)
            if attempt < maxAttempts - 1 {
                try await Task.sleep(for: delay * Double(attempt + 1))
            }
        } catch {
            throw error // do not retry 4xx and decoding errors
        }
    }
    throw lastError
}

Background Downloads — for file downloads, use URLSessionConfiguration.background(withIdentifier:). The system may terminate the process and resume the download on the next launch. The mandatory method in AppDelegate:

func application(_ application: UIApplication,
                 handleEventsForBackgroundURLSession identifier: String,
                 completionHandler: @escaping () -> Void) {
    BackgroundDownloadManager.shared.completionHandler = completionHandler
}

Without this handler, iOS will not restart the app after a background download completes.

Why a custom NetworkClient is better than ready-made libraries

Criteria Custom NetworkClient Alamofire / Moya
Framework size 0 KB ~1-2 MB
Code control Full Limited
Version dependency None Updates can break
Debugging Easier (own code) Harder (black box)
Unit tests Mocks via protocol Requires additional wrappers

In 90% of cases, a custom client covers all needs and does not pull in unnecessary dependencies. We use external libraries only when complex caching policies or WebSocket are required.

Detailed breakdown of a mistake: ignoring the SSL delegate

Consider a typical scenario: a developer adds Alamofire with ServerTrustEvaluator but forgets that they themselves create the session without a delegate. As a result, SSL pinning does not work, and the app is vulnerable to MITM attacks. In one project, we discovered that because of this, bank card data was transmitted over an unsecured connection. After replacing it with a custom NetworkClient with manual certificate verification, the problem disappeared. The savings on fixing the vulnerability — about $10,000 in potential losses. Always ensure the delegate is set.

Diagnosing problems

Tools: Charles Proxy or Proxyman for traffic inspection; Network Instrument in Xcode to analyze the number of concurrent connections and detect connection starvation; os_log with category com.apple.network for low-level logging of Network.framework.

On error NSURLErrorDomain -1001 (request timed out), first check timeoutIntervalForRequest — default is 60 seconds, which is surprisingly high for a mobile app. On NSURLErrorDomain -1200 (SSL error), check the ATS policy in Info.plist and the correctness of the server certificate chain via openssl s_client. In one project, we reduced response time by 40% simply by changing the cache policy to .reloadIgnoringLocalCacheData.

Process of work

  1. Audit the existing network layer: check session configuration, error handling, timeouts, authorization token handling.
  2. Design: API client with authorization support via URLSessionTaskDelegate or RequestInterceptor, handling 401 with token refresh.
  3. Development: implementation, Unit test coverage using a mock session (URLProtocol subclass).
  4. Testing: integration tests on a real API, behavior testing under unstable network via Network Link Conditioner.

What's Included in the Work

  • Audit of the current URLSession implementation and detection of leaks.
  • Design and implementation of a NetworkClient tailored to your requirements.
  • Setup of SSL pinning bound to a certificate or fingerprint.
  • Addition of retry logic with exponential backoff.
  • Integration of token refresh on 401.
  • Unit test coverage (100% of main scenarios).
  • Code documentation and operation instructions.
  • One month of support after delivery.

Time estimates

Task Duration
Basic API client with async/await 1 day
+ SSL pinning + retry + token refresh 2–3 days
Migration of existing network layer 2–3 days

Our Expertise

We have over 5 years of iOS development experience and have implemented network layers in 30+ applications — from startups to enterprise solutions. We know all the pitfalls of URLSession: from ATS exceptions to proper handling of Server-Sent Events. We guarantee that after our setup, your app will not crash on unstable networks and will work under poor connection conditions. Our client satisfaction rate is 100%.

Order an audit of your current network layer or development of a new one — we will assess your project in one day. Get a consultation — we will find the best solution. Additionally, refer to the URLSession Programming Guide from Apple.

Why is Native iOS Development the Best Choice for Complex Apps

The app crashes on cold start — EXC_BAD_ACCESS at the moment of initializing a singleton that accesses another singleton that hasn't been initialized yet. Or: a ViewController leaks memory because a closure captures self without [weak self], and that ViewController hangs in memory two transitions after the user left it. These are not hypothetical scenarios — they are the two most common classes of problems on iOS projects that come to us after another team.

We have been doing iOS development for over 5 years, delivered 40+ projects of varying complexity — from startups to enterprise solutions with millions of users. Each project undergoes 3 stages of Code Review, a custom set of UI tests (150+ test cases on average), and a mandatory run through Xcode Instruments before release.

Native iOS development with Swift means direct access to the platform. No middleware, no performance compromises, full control over what happens on every frame.

What Makes Native iOS Development on Swift the Choice for Enterprise Apps?

Native code guarantees compatibility with new Apple APIs on the day they are released, not after months of adaptation in cross-platform frameworks. For apps with latency-sensitive logic (financial terminals, medical monitors, AR navigation), this is critical. Swift with ARC and strict typing allows maintaining a crash-free rate of 99.9% with proper architecture.

SwiftUI or UIKit: What to Choose for Native iOS Development

By now, SwiftUI covers the vast majority of production tasks. But UIKit is not deprecated and will not disappear — Apple does not deprecate it but continues to add APIs. The real picture on large projects: a hybrid approach. SwiftUI for most screens, UIKit where SwiftUI hits limitations.

Which Scenarios Does SwiftUI Win Unconditionally

SwiftUI's declarative syntax reduces UI code by 3-5 times compared to UIKit. A settings screen with List, Toggle, Picker — that's 40 lines of SwiftUI versus 200 lines of UIKit with UITableViewDataSource delegates. Time savings on UI development reach 60%. Apple recommends starting new projects on SwiftUI (Human Interface Guidelines).

@State, @Binding, @ObservableObject (and with iOS 17, the @Observable macro) create a reactive link between data and UI without manual reloadData(). Changing a @State variable automatically redraws the affected part of the hierarchy. This works correctly if you understand how SwiftUI computes the diff — via Equatable and id in ForEach.

AsyncImage, NavigationStack with type-safe routing via NavigationPath, searchable, refreshable — these are ready-made patterns that UIKit requires implementing manually.

When UIKit Remains Necessary

UICollectionView with compositional layout and diffable data source — complex grids with different cell types, horizontal sections inside vertical scroll, dynamic cell sizes. SwiftUI LazyVGrid / LazyHGrid do not provide such control.

Custom transitions between screens. UIViewControllerAnimatedTransitioning and UIViewControllerInteractiveTransitioning — interactive pop gesture with partial progress, custom hero transition with precise frame control. SwiftUI matchedGeometryEffect covers some cases, but not all.

UITextView with TextKit 2. Rich text editor, custom attributes, custom rendering — TextKit 2 (available since iOS 16) switched to async layout, solving performance issues on long documents. SwiftUI TextEditor is a wrapper around UITextView without direct access to TextKit.

UIScrollView with custom behavior. scrollViewDidScroll, parallax effects, sticky headers with custom logic, pull-to-refresh with custom indicator. SwiftUI ScrollView with scrollPosition and onScrollGeometryChange (iOS 17) covers some cases, but not all.

How Do We Integrate SwiftUI and UIKit Step by Step

  1. Identify screens where SwiftUI gives maximum gain (lists, forms, settings) — usually 70-80% of screens.
  2. For performance-critical areas (complex collections, custom animations) leave UIKit.
  3. Use UIHostingController to embed SwiftUI views into UIKit navigation stack.
  4. For backward compatibility, wrap UIKit components via UIViewRepresentable.
  5. Coordinator pattern (UIKit) manages navigation at the flow level, screens are implemented in SwiftUI.

One pattern we use on projects: UIKit coordinator manages navigation, while the screens themselves are in SwiftUI. The coordinator creates a UIHostingController, passes ViewModel via initializer or @EnvironmentObject, and manages transitions. This gives clean separation: SwiftUI handles UI, Coordinator handles navigation.

How async/await and Combine Work Together

Before Swift 5.5, asynchronous code on iOS was built on Combine or callback chains. With the advent of async/await and Actor, concurrency has become part of the language. On new projects we use async/await as the primary tool for network calls and business logic, and Combine for reactive UI state binding.

// Correct — @MainActor guarantees UI updates on main thread
@MainActor
class UserViewModel: ObservableObject {
    @Published var user: User?
    @Published var isLoading = false

    func loadUser(id: String) async {
        isLoading = true
        defer { isLoading = false }
        do {
            user = try await userService.fetch(id: id)
        } catch {
            // handle error
        }
    }
}

Combine remains indispensable for debouncing input, merging multiple Publishers (CombineLatest, Zip), and functional processing of value streams (map, flatMap, filter). In practice, 80% of projects use both approaches, choosing the tool for the task.

iOS App Architecture

MVVM — the basic pattern. ViewModel contains logic and @Published state, SwiftUI View subscribes via @ObservedObject or @StateObject. One rule: View knows nothing about URLSession, CoreData, UserDefaults.

Clean Architecture adds Repository and UseCase layers. UserRepository abstracts the data source (network vs cache). FetchUserUseCase contains business logic. UserViewModel calls UseCase and manages UI state.

TCA (The Composable Architecture) — a stricter pattern from Point-Free. State, Action, Reducer, Effect — everything explicit, testable, composable via Scope. Works well in large teams (5+ iOS developers) where predictability is important.

What's Included in iOS App Development

Stage Deliverables
Analysis and Design Technical specification, architectural diagram, technology stack selection
Development Code compliant with App Store Review Guidelines, backend integration (REST/GraphQL)
Testing Unit tests (XCTest, coverage >75%), UI tests (XCUITest, 150+ scenarios), load testing via Firebase Test Lab
Publication Developer account setup, code signing, submission to App Store Connect
Support 30-day warranty after release, updates for new iOS versions

Tools Without Which No Release Is Complete

Xcode Instruments. Time Profiler shows where CPU spends time. Allocations — memory leaks and excessive allocations. Leaks — objects that are not freed. Before every release — a mandatory run.

Firebase Crashlytics. Crash-free rate, grouping by stack trace, breadcrumbs of events leading to crash. Set up in 30 minutes, provides visibility across the entire device fleet. On our projects, average crash-free rate is 99.8%.

Fastlane match. Manage certificates and provisioning profiles via an encrypted git repository. Eliminates the 'it builds locally but not on CI' issue once and for all. Saves up to 4 hours per build when signing manually.

XCTest + XCUITest. Unit tests for ViewModel and UseCase, UI tests for critical flows (onboarding, payment, authorization). On average, code coverage is 75%.

Typical iOS Project Mistakes and Their Solutions
Problem Solution
Memory leak due to self capture in closure Use [weak self] in all handlers where self does not need to outlive the closure
Provisioning Profile conflicts Set up Fastlane match and store certificates in a separate repository
Slow app start due to synchronous singleton initialization Move initialization to first call or use lazy var
App Store rejection due to Section 4.2 (minimal functionality) Conduct a preliminary audit using the App Store Review Guidelines checklist

Process and Timelines

Complexity Estimated Timeline
MVP (5–8 screens, basic API) 6–10 weeks
Medium app (15–25 screens) 3–5 months
Complex (payments, AR, CoreML, custom UI) 5–9 months

Cost is calculated individually after analyzing the technical specification and design. Typically, the first 2 weeks are spent on design, after which we finalize the timeline and budget.

Order turnkey development — we will evaluate your project in 2 business days and propose the optimal architecture. Contact us to discuss your task: we guarantee code quality, compliance with App Store Review Guidelines, and experience with projects of any scale. Get a consultation — we will help you choose the right stack and avoid common mistakes at the start.