Mobile Development 32 min read

Comprehensive Guide to NSURLSession: Configuration, Tasks, Delegates, Metrics, Uploads, Downloads, and Advanced Usage

This article provides an in-depth overview of NSURLSession on iOS, covering its introduction, configuration options, task types, delegate methods, HTTP/2 support, connection reuse, request redirection, metrics analysis, file upload strategies, background uploads, download handling, breakpoint resumption, and video streaming with m3u8.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Guide to NSURLSession: Configuration, Tasks, Delegates, Metrics, Uploads, Downloads, and Advanced Usage

NSURLSession was introduced in iOS 7 to replace NSURLConnection, offering a simpler API and eliminating the need to manage RunLoop objects. It supports HTTP 2.0 from iOS 9 onward, providing performance improvements.

The main components of NSURLSession are NSURLSession, NSURLSessionConfiguration, and NSURLSessionTask. Sessions can be created using sharedSession, sessionWithConfiguration:, or sessionWithConfiguration:delegate:delegateQueue: for more control.

Configuration options include defaultSessionConfiguration, ephemeralSessionConfiguration, and backgroundSessionConfigurationWithIdentifier, each affecting cookie storage, cache, and credential handling. Important properties are HTTPAdditionalHeaders, HTTPCookieStorage, URLCredentialStorage, and URLCache.

Task types include NSURLSessionDataTask for GET/POST requests, NSURLSessionUploadTask for uploads, and NSURLSessionDownloadTask for downloads with resume support. Key task methods are -resume, -suspend, and -cancel.

Delegate methods handle events such as redirection, authentication, and task completion. The delegate is strongly retained until the session becomes invalid via invalidateAndCancel or finishTasksAndInvalidate.

NSURLSessionTaskMetrics and NSURLSessionTaskTransactionMetrics provide detailed timing information for network requests, including DNS lookup, connection, TLS handshake, request/response start and end times, and resource fetch type.

File uploads should use multipart/form-data with a unique boundary. Large files should be uploaded using fromFile: to avoid high memory usage and to enable background uploads. Dynamic chunk sizing, parallel uploads, and queue management improve performance and reliability.

Downloads can be performed with NSURLSessionDownloadTask, supporting pause/resume, progress tracking, and background execution. Breakpoint resumption uses cancelByProducingResumeData: and downloadTaskWithResumeData:. Video streaming with HLS uses .m3u8 playlists and .ts segments, which can be downloaded and assembled for offline playback.

Background sessions are created with backgroundSessionConfigurationWithIdentifier, allowing uploads and downloads to continue when the app is suspended or terminated. Proper handling of delegate callbacks and completion handlers ensures tasks finish correctly.

Common pitfalls include using fromData: for uploads (causing high memory usage) and not invalidating sessions, which can lead to duplicate background tasks.

iOSMobileDevelopmentnetworkingNSURLSessiondownloadFileUpload
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.