Skip to content

Commit 9e31eba

Browse files
authored
Add docs about SignalR swift client (#34866)
1 parent 5326c88 commit 9e31eba

4 files changed

Lines changed: 264 additions & 13 deletions

File tree

aspnetcore/signalr/client-features.md

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,18 +29,18 @@ The 1.x versions of SignalR map to the 2.1 and 2.2 .NET Core releases and have t
2929

3030
The table below shows the features and support for the clients that offer real-time support. For each feature, the *minimum* version supporting this feature is listed. If no version is listed, the feature isn't supported.
3131

32-
| Feature | Server | .NET client | JavaScript client | Java client |
33-
| ---- | :-: | :-: | :-: | :-: |
34-
| Azure SignalR Service Support |2.1.0|1.0.0|1.0.0|1.0.0|
35-
| [Server-to-client Streaming](xref:signalr/streaming) |2.1.0|1.0.0|1.0.0|1.0.0|
36-
| [Client-to-server Streaming](xref:signalr/streaming) |3.0.0|3.0.0|3.0.0|3.0.0|
37-
| Automatic Reconnection ([.NET](xref:signalr/dotnet-client#handle-lost-connection), [JavaScript](xref:signalr/javascript-client#reconnect-clients)) |3.0.0|3.0.0|3.0.0||
38-
| WebSockets Transport |2.1.0|1.0.0|1.0.0|1.0.0|
39-
| Server-Sent Events Transport |2.1.0|1.0.0|1.0.0||
40-
| Long Polling Transport |2.1.0|1.0.0|1.0.0|3.0.0|
41-
| JSON Hub Protocol |2.1.0|1.0.0|1.0.0|1.0.0|
42-
| MessagePack Hub Protocol |2.1.0|1.0.0|1.0.0|5.0.0|
43-
| Client Results |7.0.0|7.0.0|7.0.0|7.0.0|
32+
| Feature | Server | .NET client | JavaScript client | Java client | Swift client |
33+
| ---- | :-: | :-: | :-: | :-: | :-: |
34+
| Azure SignalR Service Support |2.1.0|1.0.0|1.0.0|1.0.0|1.0.0-preview.1|
35+
| [Server-to-client Streaming](xref:signalr/streaming) |2.1.0|1.0.0|1.0.0|1.0.0|1.0.0-preview.1|
36+
| [Client-to-server Streaming](xref:signalr/streaming) |3.0.0|3.0.0|3.0.0|3.0.0||
37+
| Automatic Reconnection ([.NET](xref:signalr/dotnet-client#handle-lost-connection), [JavaScript](xref:signalr/javascript-client#reconnect-clients)) |3.0.0|3.0.0|3.0.0||1.0.0-preview.1|
38+
| WebSockets Transport |2.1.0|1.0.0|1.0.0|1.0.0|1.0.0-preview.1|
39+
| Server-Sent Events Transport |2.1.0|1.0.0|1.0.0||1.0.0-preview.1|
40+
| Long Polling Transport |2.1.0|1.0.0|1.0.0|3.0.0|1.0.0-preview.1|
41+
| JSON Hub Protocol |2.1.0|1.0.0|1.0.0|1.0.0|1.0.0-preview.1|
42+
| MessagePack Hub Protocol |2.1.0|1.0.0|1.0.0|5.0.0|1.0.0-preview.1|
43+
| Client Results |7.0.0|7.0.0|7.0.0|7.0.0|1.0.0-preview.1|
4444

4545
Support for enabling additional client features is tracked in [our issue tracker](https://github.com/dotnet/AspNetCore/issues).
4646

aspnetcore/signalr/supported-platforms.md

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -39,11 +39,15 @@ If the server runs IIS, the WebSockets transport requires IIS 8.0 or later on Wi
3939

4040
The [Java client](xref:signalr/java-client) supports Java 8 and later versions.
4141

42+
## Swift client
43+
44+
The [Swift client](https://github.com/dotnet/signalr-client-swift) supports Swift >= 5.10
45+
4246
## Unsupported clients
4347

4448
The following clients are available but are experimental or unofficial. The following clients aren't currently supported and may never be supported:
4549

4650
* [C++ client](https://github.com/aspnet/SignalR-Client-Cpp)
47-
* [Swift client](https://github.com/moozzyk/SignalR-Client-Swift)
51+
* [3rd party Swift client](https://github.com/moozzyk/SignalR-Client-Swift)
4852

4953
[!INCLUDE[](~/includes/SignalR/es6.md)]

aspnetcore/signalr/swift-client.md

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
---
2+
title: ASP.NET Core SignalR Swift client
3+
author: zackliu
4+
description: Overview of the ASP.NET Core SignalR Swift client library.
5+
ms.author: chenyl
6+
ms.custom: mvc, devx-track-swift
7+
ms.date: 03/20/2025
8+
uid: signalr/swift-client
9+
---
10+
11+
# ASP.NET Core SignalR Swift client
12+
13+
SignalR Swift is a client library for connecting to SignalR servers from Swift applications. This document provides an overview of how to install the client, establish a connection, handle server-to-client calls, invoke server methods, work with streaming responses, and configure automatic reconnection and other options.
14+
15+
## Install the SignalR client package
16+
17+
The SignalR Swift client library is delivered as a Swift package. You can add it to your project using the [Swift Package Manager](https://swift.org/package-manager/).
18+
19+
### Requirements
20+
21+
- Swift **>= 5.10**
22+
- macOS **>= 11.0**
23+
- iOS >= 14
24+
25+
### Install with Swift Package Manager
26+
27+
Add the SignalR Swift package as a dependency in your `Package.swift` file:
28+
29+
```swift
30+
// swift-tools-version: 5.10
31+
import PackageDescription
32+
33+
let package = Package(
34+
name: "signalr-client-app",
35+
dependencies: [
36+
.package(url: "https://github.com/dotnet/signalr-client-swift", branch: "main")
37+
],
38+
targets: [
39+
.executableTarget(name: "YourTargetName", dependencies: [.product(name: "SignalRClient", package: "signalr-client-swift")])
40+
]
41+
)
42+
```
43+
44+
After adding the dependency, import the library in your Swift code:
45+
46+
```swift
47+
import SignalRClient
48+
```
49+
50+
## Connect to a hub
51+
52+
To establish a connection, create a `HubConnectionBuilder` and configure it with the URL of your SignalR server using the `withUrl()` method. Once the connection is built, call `start()` to connect to the server:
53+
54+
```swift
55+
import SignalRClient
56+
57+
let connection = HubConnectionBuilder()
58+
.withUrl(url: "https://your-signalr-server")
59+
.build()
60+
61+
try await connection.start()
62+
```
63+
64+
## Call client methods from the hub
65+
66+
To receive messages from the server, register a handler using the `on` method. The `on` method takes the name of the hub method and a closure that will be executed when the server calls that method.
67+
68+
In the following the method name is `ReceiveMessage`. The argument names are `user` and `message`:
69+
70+
```swift
71+
await connection.on("ReceiveMessage") { (user: String, message: String) in
72+
print("\(user) says: \(message)")
73+
}
74+
```
75+
76+
The preceding code in `connection.on` runs when server-side code calls it using the <xref:Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync%2A> method:
77+
78+
[!code-csharp[Call client-side](javascript-client/samples/6.x/SignalRChat/Hubs/ChatHub.cs)]
79+
80+
SignalR determines which client method to call by matching the method name and arguments defined in `SendAsync` and `connection.on`.
81+
82+
A **best practice** is to call the `try await connection.start()` method on the `HubConnection` after `on`. Doing so ensures the handlers are registered before any messages are received.
83+
84+
85+
## Call hub methods from the client
86+
87+
Swift clients can invoke hub methods on the server using either the `invoke` or `send` methods of the HubConnection. The `invoke` method waits for the server's response and throws an error if the call fails, whereas the `send` method does not wait for a response.
88+
89+
In the following code, the method name on the hub is `SendMessage`. The second and third arguments passed to `invoke` map to the hub method's `user` and `message` arguments:
90+
91+
```swift
92+
// Using invoke, which waits for a response
93+
try await connection.invoke(method: "SendMessage", arguments: "myUser", "Hello")
94+
95+
// Using send, which does not wait for a response
96+
try await connection.send(method: "SendMessage", arguments: "myUser", "Hello")
97+
```
98+
99+
The `invoke` method returns with the return value (if any) when the method on the server returns. If the method on the server throws an error, the function throws an error.
100+
101+
## Logging
102+
103+
Swift client library includes a lightweight logging system designed for Swift applications. It provides a structured way to log messages at different levels of severity, using a customizable log handler. On Apple platforms, it leverages `os.Logger` for efficient system logging, while on other platforms, it falls back to standard console output.
104+
105+
### Log level
106+
107+
Use `HubConnectionBuilder().withLogLevel(LogLevel:)` to set the log level. Messages are logged with the specified log level and higher:
108+
109+
* `LogLevel.debug`: Detailed information useful for debugging.
110+
* `LogLevel.information`: General application messages.
111+
* `LogLevel.warning`: Warnings about potential issues.
112+
* `LogLevel.error`: Errors that need immediate attention.
113+
114+
## Client results
115+
116+
In addition to invoking server methods, the server can call methods on the client and await a response. To support this, define a client handler that returns a result from its closure:
117+
118+
```swift
119+
await connection.on("ClientResult") { (message: String) in
120+
return "client response"
121+
}
122+
```
123+
124+
For example, the server can invoke the `ClientResult` method on the client and wait for the returned value:
125+
126+
```csharp
127+
public class ChatHub : Hub
128+
{
129+
public async Task TriggerClientResult()
130+
{
131+
var message = await Clients.Client(connectionId).InvokeAsync<string>("ClientResult");
132+
}
133+
}
134+
```
135+
136+
## Working with streaming responses
137+
138+
To receive a stream of data from the server, use the `stream` method. The method returns a stream that you can iterate over asynchronously:
139+
140+
```swift
141+
let streamResult: any StreamResult<String> = try await connection.stream(method: "StreamMethod")
142+
for try await item in streamResult.stream {
143+
print("Received item: \(item)")
144+
}
145+
```
146+
147+
## Handle lost connection
148+
149+
### Automatic reconnect
150+
151+
The SignalR Swift client supports automatic reconnect. To enable it, call withAutomaticReconnect() while building the connection. Automatic reconnect is disabled by default.
152+
153+
```swift
154+
let connection = HubConnectionBuilder()
155+
.withUrl(url: "https://your-signalr-server")
156+
.withAutomaticReconnect()
157+
.build()
158+
```
159+
160+
Without parameters, withAutomaticReconnect() configures the client to wait 0, 2, 10, and 30 seconds respectively before each reconnect attempt. After four failed attempts, the client stops trying to reconnect.
161+
162+
Before starting any reconnect attempts, the `HubConnection` transitions to the `Reconnecting` state and fires its `onReconnecting` callbacks.
163+
164+
After the reconnection succeeds, the `HubConnection` transitions to the `connected` state and fires its `onReconnected` callbacks.
165+
166+
A general way to use `onReconnecting` and `onReconnected` is to mark the connection state changes:
167+
168+
```swift
169+
connection.onReconnecting { error in
170+
// connection is disconnected because of error
171+
}
172+
173+
connection.onReconnected {
174+
// connection is connected back
175+
}
176+
```
177+
178+
### Configure strategy in automatic reconnect
179+
180+
To customize the reconnect behavior, you can pass an array of numbers representing the delay in seconds before each reconnect attempt. For more granular control, pass an object that conforms to the RetryPolicy protocol.
181+
182+
#### Using an array of delay values
183+
184+
```swift
185+
let connection = HubConnectionBuilder()
186+
.withUrl(url: "https://your-signalr-server")
187+
.withAutomaticReconnect([0, 0, 1]) // Wait 0, 0, and 1 second before each reconnect attempt; stop after 3 attempts.
188+
.build()
189+
```
190+
191+
#### Using a custom retry policy
192+
193+
Implement the RetryPolicy protocol to control the reconnect timing:
194+
195+
```swift
196+
// Define a custom retry policy
197+
struct CustomRetryPolicy: RetryPolicy {
198+
func nextRetryInterval(retryContext: RetryContext) -> TimeInterval? {
199+
// For example, retry every 1 second indefinitely.
200+
return 1
201+
}
202+
}
203+
204+
let connection = HubConnectionBuilder()
205+
.withUrl(url: "https://your-signalr-server")
206+
.withAutomaticReconnect(CustomRetryPolicy())
207+
.build()
208+
```
209+
210+
## Configure timeout and keep-alive options
211+
212+
You can customize the client's timeout and keep-alive settings via the HubConnectionBuilder:
213+
214+
| Options | Default Value | Description |
215+
|---------|---------------|-------------|
216+
|withKeepAliveInterval| 15 (seconds)|Determines the interval at which the client sends ping messages and is set directly on HubConnectionBuilder. This setting allows the server to detect hard disconnects, such as when a client unplugs their computer from the network. Sending any message from the client resets the timer to the start of the interval. If the client hasn't sent a message in the ClientTimeoutInterval set on the server, the server considers the client disconnected.|
217+
|withServerTimeout| 30 (seconds)|Determines the interval at which the client waits for a response from the server before it considers the server disconnected. This setting is set directly on HubConnectionBuilder.|
218+
219+
## Configure transport
220+
221+
The SignalR Swift client supports three transports: LongPolling, ServerSentEvents, and WebSockets. By default, the client will use WebSockets if the server supports it, and fall back to ServerSentEvents and LongPolling if it doesn't. You can configure the client to use a specific transport by calling `withUrl(url:transport:)` while building the connection.
222+
223+
```swift
224+
let connection = HubConnectionBuilder()
225+
.withUrl(url: "https://your-signalr-server", transport: .webSockets) // use websocket only
226+
.build()
227+
```
228+
229+
```swift
230+
let connection = HubConnectionBuilder()
231+
.withUrl(url: "https://your-signalr-server", transport: [.webSockets, .serverSentEvents]) // use websockets and server sent events
232+
.build()
233+
```
234+
235+
## Additional resources
236+
237+
* [WebPack and TypeScript tutorial](xref:tutorials/signalr-typescript-webpack)
238+
* [Hubs](xref:signalr/hubs)
239+
* [.NET client](xref:signalr/dotnet-client)
240+
* [JavaScript client](xref:signalr/javascript-client)
241+
* [Publish to Azure](xref:signalr/publish-to-azure-web-app)
242+
* [Cross-Origin Requests (CORS)](xref:security/cors)
243+
* [Azure SignalR Service serverless documentation](/azure/azure-signalr/signalr-concept-serverless-development-config)
244+
* [Troubleshoot connection errors](xref:signalr/troubleshoot)

aspnetcore/toc.yml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -955,6 +955,9 @@ items:
955955
- name: JavaScript API reference
956956
href: /javascript/api/@microsoft/signalr/
957957
displayName: signalr
958+
- name: Swift client
959+
uid: signalr/swift-client
960+
displayName: signalr
958961
- name: Host and scale
959962
displayName: signalr
960963
items:

0 commit comments

Comments
 (0)