2021 Safari & WebSystem Services
WWDC21 · 20 min · Safari & Web / System Services
Accelerate networking with HTTP/3 and QUIC
The web is changing, and the next major version of HTTP is here. Learn how HTTP/3 reduces latency and improves reliability for your app and discover how its underlying transport, QUIC, unlocks new innovations in your own custom protocols using new transport functionality and multi-streaming connection groups.
Watch at developer.apple.com ↗Code shown on screen · 5 snippets
Using QUIC in your app
// Create a connection using QUIC
let connection = NWConnection(host: "example.com", port: 443, using: .quic(alpn: ["myproto"]))
// Set the state update handler to be notified when the connection is ready
connection.stateUpdateHandler = { newState in
switch newState {
case .ready:
print("Connected using QUIC!")
default:
break
}
}
// Start the connection with callback queue
connection.start(queue: queue) Establish a tunnel with NWMultiplexGroup
// Establish a tunnel with NWMultiplexGroup
// Create a group
let descriptor = NWMultiplexGroup(to: .hostPort(host: "example.com", port: 443))
let group = NWConnectionGroup(with: descriptor, using: .quic(alpn: ["myproto"]))
// Set the state update handler to be notified when the group is ready
group.stateUpdateHandler = { newState in
switch newState {
case .ready:
print("Connected using QUIC!")
default:
break
}
}
// Start the group with callback queue
group.start(queue: queue) Manage streams with NWConnectionGroup
// Manage streams with NWConnectionGroup
// Create a new outgoing stream
let connection = NWConnection(from: group)
// Receive new incoming streams initiated by the remote endpoint
group.newConnectionHandler = { newConnection in
// Set state update handler on incoming stream
newConnection.stateUpdateHandler = { newState in
// Handle stream states
}
// Start the incoming stream
newConnection.start(queue: queue)
} Receive incoming QUIC tunnels from NWListener
// Receive incoming QUIC tunnels from NWListener
// Set the new connection group handler
listener.newConnectionGroupHandler = { group in
group.stateUpdateHandler = { newState in
// Handle tunnel states
}
group.newConnectionHandler = { stream in
// Set up and start new incoming streams
}
group.start(queue: queue)
} Access QUIC metadata
// Access QUIC metadata to learn about and modify streams
// Find the stream ID of a particular QUIC stream
if let metadata = connection.metadata(definition: NWProtocolQUIC.definition)
as? NWProtocolQUIC.Metadata {
print("QUIC Stream ID is \(metadata.streamIdentifier)")
// Some time later...
// Set the application error, if appropriate, before cancelling the stream
metadata.applicationError = 0x100
connection.cancel()
} Related sessions
-
19 min -
24 min -
14 min -
34 min -
23 min