iOS Video with AVFoundation: HLS, Covers and Compression
|
This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production. |
Baseline date: 2026-10-07. iOS plays HLS natively, which is why the packaging in
video streaming: HLS, DASH and CMAF is aimed at it first. Capturing
video, the photo library and the VideoPlayer basics are in
Camera, Media and Photos. This page adds the media-pipeline pieces. API
availability changes with the iOS version, so check Apple’s documentation for the deployment target of your app.
Playing HLS
import AVKit
import SwiftUI
struct VideoScreen: View {
@State private var player = AVPlayer(url: URL(string: "https://cdn.example.com/videos/42/master.m3u8")!)
var body: some View {
VideoPlayer(player: player)
.aspectRatio(16.0 / 9.0, contentMode: .fit)
.onDisappear { player.pause() }
}
}
AVPlayer chooses the rendition from the multivariant playlist and switches by segment. You can bound the choice on the
AVPlayerItem with preferredPeakBitRate, preferredPeakBitRateForExpensiveNetworks (iOS 15 and later, for example
on cellular) and preferredMaximumResolution. Private video
works with signed cookies passed to the asset through the documented AVURLAssetHTTPCookiesKey option (an array of
HTTPCookie). A token in a request header is usually set with the AVURLAssetHTTPHeaderFieldsKey option, but that key is
exported by AVFoundation without being declared in its public headers or documented, so prefer cookies or a signed URL, and
treat the header key as something that may change between releases. The requirements Apple states for streams (keyframes every two seconds, six
second segments) are in
video encoding fundamentals. Reference:
AVPlayer and
HTTP Live Streaming.
Cover frames with AVAssetImageGenerator
import AVFoundation
import UIKit
func coverImage(for url: URL, at seconds: Double) async throws -> UIImage {
let asset = AVURLAsset(url: url)
let generator = AVAssetImageGenerator(asset: asset)
generator.appliesPreferredTrackTransform = true // honour the rotation of the recording
generator.maximumSize = CGSize(width: 1280, height: 1280) // never decode a full 4K frame
let time = CMTime(seconds: seconds, preferredTimescale: 600)
let (cgImage, _) = try await generator.image(at: time) // async API from iOS 16
return UIImage(cgImage: cgImage)
}
appliesPreferredTrackTransform matters: iPhones record landscape pixels with a rotation flag, so without it the cover is
sideways. By default the generator picks the nearest frame with a tolerance, and you can set
requestedTimeToleranceBefore/After to .zero for an exact frame, which is slower. Compress the result to JPEG or HEIC
with UIImage.jpegData(compressionQuality:) and upload it as the poster. Reference:
AVAssetImageGenerator and
video covers and thumbnails.
Compressing with AVAssetExportSession
func compress(_ source: URL, to destination: URL) async throws {
let asset = AVURLAsset(url: source)
guard let session = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset1280x720) else {
throw CocoaError(.fileWriteUnknown)
}
session.outputURL = destination
session.outputFileType = .mp4
session.shouldOptimizeForNetworkUse = true // moov atom first, like faststart
await session.export() // iOS 18 offers export(to:as:) with progress states
if session.status != .completed { throw session.error ?? CocoaError(.fileWriteUnknown) }
}
Presets such as AVAssetExportPreset1280x720 and AVAssetExportPresetMediumQuality pick the size and bit rate for you, and
AVAssetExportPresetHEVCHighestQuality produces HEVC. Check AVAssetExportSession.exportPresets(compatibleWith:) for what a
given asset supports. For full control of codec and bit rate, use AVAssetReader and AVAssetWriter. HEVC from the camera
is small but not playable in every browser, which is why the server transcodes anyway, see
device-side compression and uploads. Reference:
AVAssetExportSession.
Background uploads with URLSession
An upload must survive the app being suspended. A background URLSession hands the transfer to the system:
final class Uploader: NSObject, URLSessionTaskDelegate {
private lazy var session: URLSession = {
let config = URLSessionConfiguration.background(withIdentifier: "com.example.uploads")
config.isDiscretionary = false
config.sessionSendsLaunchEvents = true
return URLSession(configuration: config, delegate: self, delegateQueue: nil)
}()
func upload(file: URL, to presignedURL: URL, contentType: String) {
var request = URLRequest(url: presignedURL)
request.httpMethod = "PUT"
request.setValue(contentType, forHTTPHeaderField: "Content-Type")
session.uploadTask(with: request, fromFile: file).resume() // background sessions require a file, not Data
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
// tell the API the upload is complete, or retry; see the pipeline page
}
}
The URL is the pre-signed PUT URL from the backend, see
upload pipelines. Implement
application(_:handleEventsForBackgroundURLSession:completionHandler:) to be woken when transfers finish in the background.
Reference: URL loading
system, background transfers.
Worked example: video 42 from the camera roll to the CDN
The running example is the video 42 of the backend pages. The phone records it as 1920 by 1080 pixels with a rotation
flag, because iPhones store landscape pixels and rotate on playback. The app makes a poster, compresses a copy and uploads
both, and the server then produces the ladder that AVPlayer plays.
A command-line Swift program was run on a Mac to check what these calls really do. It wrote a 6 second 1920 by 1080 clip
with AVAssetWriter (H.264, 30 frames per second, a keyframe every 30 frames, transform set to a 90 degree rotation),
and then called the functions of this page on it. The frames are flat colours and a moving circle, so the bit rates are far
below those of a real recording. The dimensions, rotation and timing results do not depend on the content:
| Step | Result |
|---|---|
The source clip |
natural size 1920 by 1080, displayed 1080 by 1920, 6.0 s |
Cover with |
1280 by 720, sideways |
The same with |
720 by 1280, upright |
Request at 2.40 s, default tolerance |
the frame at 2.767 s |
Request at 2.40 s, tolerance before and after |
the frame at 2.400 s |
|
720 by 1280, 6.0 s, rotation baked into the pixels |
|
320 by 568 |
|
1080 by 1920 |
Three lessons follow. The preset fits the video into a 1280 by 720 box after the rotation, so a portrait recording comes out at 720 by 1280, and the exported file has an identity transform, so no rotation flag is left for a player to ignore. A preset named for a size is a maximum, not an exact size: the medium quality preset produced 320 by 568, which is too small for a poster or a detail screen. And the default tolerance of the image generator does not mean "the frame before the time you asked for". It returns a frame that is cheap to decode near the request, which here was later than the request (2.767 s for 2.40 s). For a poster that is fine, and for a frame-accurate scrubber it is not.
AVAssetExportSession.exportPresets(compatibleWith:) was deprecated in macOS 13 and iOS 16 in favour of an asynchronous
check (compatibility(ofExportPreset:with:outputFileType:)), which is the way to decide at run time whether HEVC export is
possible for a given asset:
func canExportHEVC(_ asset: AVAsset) async -> Bool {
await AVAssetExportSession.compatibility(ofExportPreset: AVAssetExportPresetHEVC1920x1080, with: asset, outputFileType: .mp4)
}
Exporting with progress
From iOS 18 (macOS 15) the export has a throwing method that takes the destination and a stream of states, and the older
export() is deprecated. The code below was run on the generated clip. Keep the
older callback form for deployment targets before iOS 18:
func compress(_ source: URL, to destination: URL, progress: @escaping (Float) -> Void) async throws {
let asset = AVURLAsset(url: source)
guard let session = AVAssetExportSession(asset: asset, presetName: AVAssetExportPreset1280x720) else {
throw CocoaError(.fileWriteUnknown)
}
session.shouldOptimizeForNetworkUse = true
let watcher = Task {
for await state in session.states(updateInterval: 0.5) {
if case .exporting(let value) = state { progress(Float(value.fractionCompleted)) }
}
}
defer { watcher.cancel() }
try await session.export(to: destination, as: .mp4) // throws on failure or cancellation
}
Remove a destination file that already exists before the call: a second export to the same path failed with "Cannot Save". The state stream reports .exporting values up to the last progress update and then a final state, so set the bar to 100 percent when the call returns instead of waiting for a value of 1. Drive a progress
bar from the callback, and keep the export in a Task that the screen can cancel. Exporting is CPU and battery heavy, so
do it once per upload and keep the file until the API confirms the upload.
Limiting the rendition and watching it
The playback side has the same two inputs as on Android, metered network and view size, with different names. The
AVPlayerItem properties below bound what the multivariant playlist may select:
let item = AVPlayerItem(asset: AVURLAsset(url: manifestURL))
item.preferredPeakBitRate = 3_000_000 // bits per second, 0 means no limit
item.preferredPeakBitRateForExpensiveNetworks = 1_000_000 // cellular and personal hotspots, iOS 15 and later
item.preferredMaximumResolution = CGSize(width: 1280, height: 720) // tile or screen size, in pixels
With the ladder of the backend pages (360p at 0.8, 540p at 1.8, 720p at 3, 1080p at 6 Mbit/s), a 1 Mbit/s ceiling on expensive networks leaves only the 360p rung, so a 1.8 Mbit/s ceiling is the lowest that still allows 540p. The player never selects a rung above the ceiling, so set the ceiling from the rung you want to allow, not from a round number. What the player actually chose is in the access log, which posts a notification for each new entry:
let token = NotificationCenter.default.addObserver(
forName: AVPlayerItem.newAccessLogEntryNotification, object: item, queue: .main
) { _ in
guard let event = item.accessLog()?.events.last else { return }
analytics.record(indicated: event.indicatedBitrate, // the rendition's declared bit rate
observed: event.observedBitrate, // measured throughput
dropped: event.numberOfDroppedVideoFrames)
}
Compare indicatedBitrate with the ladder to see which rung viewers sit on, and observedBitrate with the rung to see
how much headroom the network gives. Remove the observer when the item is replaced.
Background uploads of the exported file
The exported file is the input of the upload. Two settings of the configuration matter for large video: waitsForConnectivity
lets a task that starts offline wait instead of failing, and allowsExpensiveNetworkAccess set to false keeps the
transfer off cellular. For files above a few hundred MiB, split the upload into parts, each in its own file, and track the
parts that finished, as in
device-side compression and uploads. The completion
handler of the session identifies a task by its taskDescription, so set it to the part number:
var request = URLRequest(url: partURL)
request.httpMethod = "PUT"
let task = session.uploadTask(with: request, fromFile: partFile)
task.taskDescription = "upload-\(uploadId)-part-\(number)" // read back in didCompleteWithError, also after a relaunch
task.resume()
After a relaunch, await session.allTasks returns the tasks that the system still holds, with their descriptions, so the app
can rebuild which parts are in flight before it asks the service which parts it has.
Related pages
-
Video Encoding Fundamentals defines the ladder that the server produces from the uploaded file.
-
Video Playback and Streaming is the browser counterpart.