One Logo Pool Ball
Network · IOS API REFERENCE

NWConnection

class · iOS 12.0+ · SDK 27.1

final class NWConnection

An NWConnection is an object that represents a bi-directional data pipe between a local endpoint and a remote endpoint. A connection handles establishment of any transport, security, or application-level protocols required to transmit and receive user data. Multiple protocol instances may be attempted during the establishment phase of the connection.

Members (34)

get · iOS 12.0+

parameters

TypeScript
get parameters(): NWParameters
Swift declaration
final let parameters: NWParameters

The set of parameters with which the connection was created

get · iOS 12.0+

currentPath

TypeScript
get currentPath(): (NWPath) | null
Swift declaration
final var currentPath: NWPath? { get }

Current path for the connection, which can be used to extract interface and effective endpoint information

method · iOS 12.0+

forceCancel

TypeScript
forceCancel(): void
Swift declaration
final func forceCancel()

A variant of cancel that performs non-graceful closure of the transport.

method · iOS 12.0+

receiveMessage

TypeScript
receiveMessage(completion: ((arg0: (ArrayBuffer) | null, arg1: (NWConnection_ContentContext) | null, arg2: boolean, arg3: (NWError) | null) => void)): void
Swift declaration
@preconcurrency final func receiveMessage(completion: @escaping @Sendable (Data?, NWConnection.ContentContext?, Bool, NWError?) -> Void)

Receive complete message content from the connection, waiting for the content to be marked complete (or encounter an error) before delivering the callback. This is useful for datagram or message-based protocols like UDP. See receive(minimumIncompleteLength:, maximumLength:, completion:) for a description of the completion handler.

get · iOS 12.0+

debugDescription

TypeScript
get debugDescription(): string
Swift declaration
final var debugDescription: String { get }

A textual representation of this instance, suitable for debugging. Calling this property directly is discouraged. Instead, convert an instance of any type to a string by using the `String(reflecting:)` initializer. This initializer works with any type, and uses the custom `debugDescription` property for types that conform to `CustomDebugStringConvertible`: struct Point: CustomDebugStringConvertible { let x: Int, y: Int var debugDescription: String { return "(\(x), \(y))" } } let p = Point(x: 21, y: 30) let s = String(reflecting: p) print(s) // Prints "(21, 30)" The conversion of `p` to a string in the assignment to `s` uses the `Point` type's `debugDescription` property.

get · iOS 12.0+

pathUpdateHandler

TypeScript
get pathUpdateHandler(): (((arg0: NWPath) => Promise<void>)) | null
Swift declaration
@preconcurrency final var pathUpdateHandler: (@Sendable (NWPath) -> Void)? { get set }

Set a block to be called when the connection's path has changed, which may be called multiple times until the connection is cancelled.

set · iOS 12.0+

pathUpdateHandler

TypeScript
set pathUpdateHandler(value: (((arg0: NWPath) => void)) | null)
Swift declaration
@preconcurrency final var pathUpdateHandler: (@Sendable (NWPath) -> Void)? { get set }

Set a block to be called when the connection's path has changed, which may be called multiple times until the connection is cancelled.

get · iOS 12.0+

stateUpdateHandler

TypeScript
get stateUpdateHandler(): (((arg0: NWConnection_State) => Promise<void>)) | null
Swift declaration
@preconcurrency final var stateUpdateHandler: (@Sendable (NWConnection.State) -> Void)? { get set }

Set a block to be called when the connection's state changes, which may be called multiple times until the connection is cancelled.

set · iOS 12.0+

stateUpdateHandler

TypeScript
set stateUpdateHandler(value: (((arg0: NWConnection_State) => void)) | null)
Swift declaration
@preconcurrency final var stateUpdateHandler: (@Sendable (NWConnection.State) -> Void)? { get set }

Set a block to be called when the connection's state changes, which may be called multiple times until the connection is cancelled.

get · iOS 13.0+

maximumDatagramSize

TypeScript
get maximumDatagramSize(): number
Swift declaration
final var maximumDatagramSize: Int { get }

Retrieve the maximum datagram size that can be sent on the connection. Any datagrams sent should be less than or equal to this size.

method · iOS 14.0+

receiveDiscontiguous

TypeScript
receiveDiscontiguous(minimumIncompleteLength: number, maximumLength: number, completion: ((arg0: (_Dispatch_DispatchData) | null, arg1: (NWConnection_ContentContext) | null, arg2: boolean, arg3: (NWError) | null) => void)): void
Swift declaration
@preconcurrency final func receiveDiscontiguous(minimumIncompleteLength: Int, maximumLength: Int, completion: @escaping @Sendable (DispatchData?, NWConnection.ContentContext?, Bool, NWError?) -> Void)

Receive data from a connection. This behaves in the same manner as `receive` differing only in providing content in the form of DispatchData. When the underlying data is not contiguous, using DispatchData can avoid copying the data to a contiguous buffer.

method · iOS 12.0+

cancelCurrentEndpoint

TypeScript
cancelCurrentEndpoint(): void
Swift declaration
final func cancelCurrentEndpoint()

Cancel the currently connected endpoint, causing the connection to fall through to the next endpoint if available, or to go to the waiting state if no more endpoints are available.

get · iOS 12.0+

viabilityUpdateHandler

TypeScript
get viabilityUpdateHandler(): (((arg0: boolean) => Promise<void>)) | null
Swift declaration
@preconcurrency final var viabilityUpdateHandler: (@Sendable (Bool) -> Void)? { get set }

Set a block to be called when the connection's viability changes, which may be called multiple times until the connection is cancelled. Connections that are not currently viable do not have a route, and packets will not be sent or received. There is a possibility that the connection will become viable again when network connectivity changes.

set · iOS 12.0+

viabilityUpdateHandler

TypeScript
set viabilityUpdateHandler(value: (((arg0: boolean) => void)) | null)
Swift declaration
@preconcurrency final var viabilityUpdateHandler: (@Sendable (Bool) -> Void)? { get set }

Set a block to be called when the connection's viability changes, which may be called multiple times until the connection is cancelled. Connections that are not currently viable do not have a route, and packets will not be sent or received. There is a possibility that the connection will become viable again when network connectivity changes.

get · iOS 12.0+

betterPathUpdateHandler

TypeScript
get betterPathUpdateHandler(): (((arg0: boolean) => Promise<void>)) | null
Swift declaration
@preconcurrency final var betterPathUpdateHandler: (@Sendable (Bool) -> Void)? { get set }

A better path being available indicates that the system thinks there is a preferred path or interface to use, compared to the one this connection is actively using. As an example, the connection is established over an expensive cellular interface and an unmetered Wi-Fi interface is now available. Set a block to be called when a better path becomes available or unavailable, which may be called multiple times until the connection is cancelled. When a better path is available, if it is possible to migrate work from this connection to a new connection, create a new connection to the endpoint. Continue doing work on this connection until the new connection is ready. Once ready, transition work to the new connection and cancel this one.

set · iOS 12.0+

betterPathUpdateHandler

TypeScript
set betterPathUpdateHandler(value: (((arg0: boolean) => void)) | null)
Swift declaration
@preconcurrency final var betterPathUpdateHandler: (@Sendable (Bool) -> Void)? { get set }

A better path being available indicates that the system thinks there is a preferred path or interface to use, compared to the one this connection is actively using. As an example, the connection is established over an expensive cellular interface and an unmetered Wi-Fi interface is now available. Set a block to be called when a better path becomes available or unavailable, which may be called multiple times until the connection is cancelled. When a better path is available, if it is possible to migrate work from this connection to a new connection, create a new connection to the endpoint. Continue doing work on this connection until the new connection is ready. Once ready, transition work to the new connection and cancel this one.

method · iOS 13.0+

startDataTransferReport

TypeScript
startDataTransferReport(): NWConnection_PendingDataTransferReport
Swift declaration
final func startDataTransferReport() -> NWConnection.PendingDataTransferReport

Start a new pending data transfer report on a connection. Multiple reports may be created for a single NWConnection. The report begins capturing data when the connection moves to the .ready state, or when the report is created (whichever occurs last).

method · iOS 13.0+

requestEstablishmentReport

TypeScript
requestEstablishmentReport(queue: _Dispatch_DispatchQueue, completion: ((arg0: (NWConnection_EstablishmentReport) | null) => void)): void
Swift declaration
@preconcurrency final func requestEstablishmentReport(queue: DispatchQueue, completion: @escaping @Sendable (NWConnection.EstablishmentReport?) -> Void)

Asynchronously request the establishment report for this connection. If called prior to the connection being in the .ready state, the report will be nil. The completion handler will be invoked exactly once on the provided DispatchQueue.

method · iOS 14.0+

receiveMessageDiscontiguous

TypeScript
receiveMessageDiscontiguous(completion: ((arg0: (_Dispatch_DispatchData) | null, arg1: (NWConnection_ContentContext) | null, arg2: boolean, arg3: (NWError) | null) => void)): void
Swift declaration
@preconcurrency final func receiveMessageDiscontiguous(completion: @escaping @Sendable (DispatchData?, NWConnection.ContentContext?, Bool, NWError?) -> Void)

Receive complete message content from the connection, waiting for the content to be marked complete (or encounter an error) before delivering the callback. This behaves in the same manner as `receiveMessage` differing only in providing the content in the form of DispatchData. When the underlying data is not contiguous, using DispatchData can avoid copying the data to a contiguous buffer.

init · iOS 12.0+

init

TypeScript
static initToUsing(to: NWEndpoint, using: NWParameters): NWConnection
Swift declaration
init(to: NWEndpoint, using: NWParameters)

Create a new outbound connection to an endpoint, with parameters. The parameters determine the protocols to be used for the connection, and their options. - Parameter to: The remote endpoint to which to connect. - Parameter using: The parameters define which protocols and path to use.

init · iOS 15.0+

init

TypeScript
static initFromToUsing(from: NWConnectionGroup, to?: (NWEndpoint) | null, using?: (NWProtocolOptions) | null): (NWConnection) | null
Swift declaration
convenience init?(from: NWConnectionGroup, to: NWEndpoint? = nil, using: NWProtocolOptions? = nil)

Creates a new connection from the connection group. For a multiplex connection group, this means that a new stream is opened. For non-multiplex connection groups, a connection to the specified endpoint will be returned if allowed by the group descriptor. - Parameter from: The connection group to create a connection from. - Parameter to: The remote endpoint to create the connection to (if applicable). - Parameter using: Protocol options to apply to the new connection (if applicable).

init · iOS 12.0+

init

TypeScript
static initHostPortUsing(host: NWEndpoint_Host, port: NWEndpoint_Port, using: NWParameters): NWConnection
Swift declaration
convenience init(host: NWEndpoint.Host, port: NWEndpoint.Port, using: NWParameters)

Create a new outbound connection to a hostname and port, with parameters. The parameters determine the protocols to be used for the connection, and their options. - Parameter host: The remote hostname to which to connect. - Parameter port: The remote port to which to connect. - Parameter using: The parameters define which protocols and path to use.

method · iOS 12.0+

send

TypeScript
sendContentContentContextIsCompleteCompletion(content: (ArrayBuffer) | null, contentContext: NWConnection_ContentContext, isComplete: boolean, completion: NWConnection_SendCompletion): void
Swift declaration
@preconcurrency final func send(content: Data?, contentContext: NWConnection.ContentContext = .defaultMessage, isComplete: Bool = true, completion: NWConnection.SendCompletion)

Send data on a connection. This may be called before the connection is ready, in which case the send will be enqueued until the connection is ready to send. This is an asynchronous send and the completion block can be used to determine when the send is complete. There is nothing preventing a client from issuing an excessive number of outstanding sends. To minimize memory footprint and excessive latency as a consequence of buffer bloat, it is advisable to keep a low number of outstanding sends. The completion block can be used to pace subsequent sends. - Parameter content: The data to send on the connection. May be nil if this send marks its context as complete, such as by sending .finalMessage as the context and marking isComplete to send a write-close. - Parameter contentContext: The context associated with the content, which represents a logical message to be sent on the connection. All content sent within a single context will be sent as an in-order unit, up until the point that the context is marked complete (see isComplete). Once a context is marked complete, it may be re-used as a new logical message. Protocols like TCP that cannot send multiple independent messages at once (serial streams) will only start processing a new context once the prior context has been marked complete. Defaults to .defaultMessage. - Parameter isComplete: A flag indicating if the caller's sending context (logical message) is now complete. Until a context is marked complete, content sent for other contexts may not be sent immediately (if the protocol requires sending bytes serially, like TCP). For datagram protocols, like UDP, isComplete indicates that the content represents a complete datagram. When sending using streaming protocols like TCP, isComplete can be used to mark the end of a single message on the stream, of which there may be many. However, it can also indicate that the connection should send a "write close" (a TCP FIN) if the sending context is the final context on the connection. Specifically, to send a "write close", pass .finalMessage or .defaultStream for the context (or create a custom context and set .isFinal), and pass true for isComplete. - Parameter completion: A completion handler (.contentProcessed) to notify the caller when content has been processed by the connection, or a marker that this data is idempotent (.idempotent) and may be sent multiple times as fast open data.

method · iOS 13.0+

send

TypeScript
sendContentContentContextIsCompleteCompletion50355(content: (ArrayBuffer) | null, contentContext: NWConnection_ContentContext, isComplete: boolean, completion: NWConnection_SendCompletion): void
Swift declaration
@preconcurrency final func send<Content>(content: Content?, contentContext: NWConnection.ContentContext = .defaultMessage, isComplete: Bool = true, completion: NWConnection.SendCompletion) where Content : DataProtocol

Send a DataProtocol object on a connection. This function follows the same behavior as the send() function that takes Data. - Parameter content: The DataProtocol object to send on the connection. May be nil if this send marks its context as complete, such as by sending .finalMessage as the context and marking isComplete to send a write-close. - Parameter contentContext: The context associated with the content, which represents a logical message to be sent on the connection. All content sent within a single context will be sent as an in-order unit, up until the point that the context is marked complete (see isComplete). Once a context is marked complete, it may be re-used as a new logical message. Protocols like TCP that cannot send multiple independent messages at once (serial streams) will only start processing a new context once the prior context has been marked complete. Defaults to .defaultMessage. - Parameter isComplete: A flag indicating if the caller's sending context (logical message) is now complete. Until a context is marked complete, content sent for other contexts may not be sent immediately (if the protocol requires sending bytes serially, like TCP). For datagram protocols, like UDP, isComplete indicates that the content represents a complete datagram. When sending using streaming protocols like TCP, isComplete can be used to mark the end of a single message on the stream, of which there may be many. However, it can also indicate that the connection should send a "write close" (a TCP FIN) if the sending context is the final context on the connection. Specifically, to send a "write close", pass .finalMessage or .defaultStream for the context (or create a custom context and set .isFinal), and pass true for isComplete. - Parameter completion: A completion handler (.contentProcessed) to notify the caller when content has been processed by the connection, or a marker that this data is idempotent (.idempotent) and may be sent multiple times as fast open data.

method · iOS 12.0+

batch

TypeScript
batch(block: (() => void)): void
Swift declaration
final func batch(_ block: () -> Void)

Batching allows multiple send or receive calls provides a hint to the connection that the operations should be coalesced to improve efficiency. Calls other than send and receive will not be affected.

get · iOS 12.0+

queue

TypeScript
get queue(): (_Dispatch_DispatchQueue) | null
Swift declaration
final var queue: DispatchQueue? { get }

Get queue used for delivering block handlers, such as stateUpdateHandler, pathUpdateHandler, connectionProgressUpdateHandler viabilityUpdateHandler, betterPathUpdateHandler, and completions for send and receive. If the connection has not yet been started, the queue will be nil. Once the connection has been started, the queue will be non-nil.

method · iOS 12.0+

start

TypeScript
start(queue: _Dispatch_DispatchQueue): void
Swift declaration
final func start(queue: DispatchQueue)

Start the connection and provide a dispatch queue for callback blocks. Starts the connection, which will cause the connection to evaluate its path, do resolution, and try to become ready (connected). NWConnection establishment is asynchronous. A stateUpdateHandler may be used to determine when the state changes. If the connection cannot be established, the state will transition to waiting with an associated error describing the reason. If an unrecoverable error is encountered, the state will transition to failed with an associated NWError value. If the connection is established, the state will transition to ready. Start should only be called once on a connection, and multiple calls to start will be ignored.

get · iOS 12.0+

state

TypeScript
get state(): NWConnection_State
Swift declaration
final var state: NWConnection.State { get }

Access the current state of the connection

method · iOS 12.0+

cancel

TypeScript
cancel(): void
Swift declaration
final func cancel()

Cancel the connection, and cause all update handlers to be cancelled. Cancel is asynchronous. The last callback will be to the stateUpdateHandler with the cancelled state. After the stateUpdateHandlers are called with the cancelled state, all blocks are released to break retain cycles. Calls to cancel after the first one are ignored.

init · iOS 15.0+

init

TypeScript
static initMessage(message: NWConnectionGroup_Message): (NWConnection) | null
Swift declaration
convenience init?(message: NWConnectionGroup.Message)

Creates a new connection, corresponding to the received message, that can be used to read the remainder of a partial message or to send a large response to the endpoint that sent this message. - Parameter message: The message received on a connection group that the new connection should be created for.

method · iOS 12.0+

receive

TypeScript
receive(minimumIncompleteLength: number, maximumLength: number, completion: ((arg0: (ArrayBuffer) | null, arg1: (NWConnection_ContentContext) | null, arg2: boolean, arg3: (NWError) | null) => void)): void
Swift declaration
@preconcurrency final func receive(minimumIncompleteLength: Int, maximumLength: Int, completion: @escaping @Sendable (Data?, NWConnection.ContentContext?, Bool, NWError?) -> Void)

Receive data from a connection. This may be called before the connection is ready, in which case the receive request will be queued until the connection is ready. The completion handler will be invoked exactly once for each call, so the client must call this function multiple times to receive multiple chunks of data. For protocols that support flow control, such as TCP, calling receive opens the receive window. If the client stops calling receive, the receive window will fill up and the remote peer will stop sending. - Parameter minimumIncompleteLength: The minimum length to receive from the connection, until the content is complete. - Parameter maximumLength: The maximum length to receive from the connection in a single completion. - Parameter completion: A receive completion is invoked exactly once for a call to receive(...). The completion indicates that the requested content has been received (in which case the content is delivered), or else an error has occurred. Parameters to the completion are: - content: The received content, as constrained by the minimum and maximum length. This may be nil if the message or stream is complete (without any more data to deliver), or if an error was encountered. - contentContext: Content context describing the received content. This includes protocol metadata that lets the caller introspect information about the received content (such as flags on a packet). - isComplete: An indication that this context (a message or stream, for example) is now complete. For protocols such as TCP, this will be marked when the entire stream has be closed in the reading direction. For protocols such as UDP, this will be marked when the end of a datagram has been reached. - error: An error will be sent if the receive was terminated before completing. There may still be content delivered along with the error, but this content may be shorter than the requested ranges. An error will be sent for any outstanding receives when the connection is cancelled.

method · iOS 12.0+

restart

TypeScript
restart(): void
Swift declaration
final func restart()

NWConnections will normally re-attempt on network changes. This function causes a connection that is in the waiting state to re-attempt even without a network change.

get · iOS 12.0+

endpoint

TypeScript
get endpoint(): NWEndpoint
Swift declaration
final let endpoint: NWEndpoint

The remote endpoint of the connection

method · iOS 12.0+

metadata

TypeScript
metadata(definition: NWProtocolDefinition): (NWProtocolMetadata) | null
Swift declaration
final func metadata(definition: NWProtocolDefinition) -> NWProtocolMetadata?

Access connection-wide protocol metadata on the connection. This allows access to state for protocols like TCP and TLS that have long-term state.

Skipped declarations

No declarations were skipped in this snapshot.

All Network types →