Skip to content

Commit b825fc9

Browse files
authored
Update swift client docs
1 parent f182b9a commit b825fc9

File tree

1 file changed

+228
-0
lines changed

1 file changed

+228
-0
lines changed

aspnetcore/signalr/swift-client.md

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
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: 2/12/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+
24+
### Install with Swift Package Manager
25+
26+
Add the SignalR Swift package as a dependency in your `Package.swift` file:
27+
28+
```swift
29+
// swift-tools-version: 5.10
30+
import PackageDescription
31+
32+
let package = Package(
33+
name: "signalr-client-app",
34+
dependencies: [
35+
.package(url: "https://github.com/Azure/signalr-swift")
36+
],
37+
targets: [
38+
.target(
39+
name: "YourTargetName",
40+
dependencies: [
41+
.product(name: "SignalRClient", package: "signalr-swift")
42+
]
43+
)
44+
]
45+
)
46+
```
47+
48+
After adding the dependency, import the library in your Swift code:
49+
50+
```swift
51+
import SignalRClient
52+
```
53+
54+
## Connect to a hub
55+
56+
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:
57+
58+
```swift
59+
import SignalRClient
60+
61+
let connection = HubConnectionBuilder()
62+
.withUrl(url: "https://your-signalr-server")
63+
.build()
64+
65+
try await connection.start()
66+
```
67+
68+
### Cross-origin connections (CORS)
69+
70+
Typically, browsers load connections from the same domain as the requested page. However, there are occasions when a connection to another domain is required.
71+
72+
When making [cross domain requests](xref:signalr/security#cross-origin-resource-sharing), the client code ***must*** use an absolute URL instead of a relative URL. For cross domain requests, change `.withUrl(url: "/chathub")` to `.withUrl(url: "https://{App domain name}/chathub")`.
73+
74+
To prevent a malicious site from reading sensitive data from another site, [cross-origin connections](xref:security/cors) are disabled by default. To allow a cross-origin request, enable [CORS](xref:security/cors):
75+
76+
[!code-csharp[](javascript-client/samples/6.x/SignalRChat/Program.cs?highlight=8-18,35-36,39)]
77+
78+
<xref:Microsoft.AspNetCore.Builder.CorsMiddlewareExtensions.UseCors%2A> must be called before calling <xref:Microsoft.AspNetCore.Builder.HubEndpointRouteBuilderExtensions.MapHub%2A>.
79+
80+
## Call client methods from the hub
81+
82+
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.
83+
84+
In the following the method name is `ReceiveMessage`. The argument names are `user` and `message`:
85+
86+
```swift
87+
await connection.on("ReceiveMessage") { (user: String, message: String) in
88+
print("\(user) says: \(message)")
89+
}
90+
```
91+
92+
The preceding code in `connection.on` runs when server-side code calls it using the <xref:Microsoft.AspNetCore.SignalR.ClientProxyExtensions.SendAsync%2A> method:
93+
94+
[!code-csharp[Call client-side](javascript-client/samples/6.x/SignalRChat/Hubs/ChatHub.cs)]
95+
96+
SignalR determines which client method to call by matching the method name and arguments defined in `SendAsync` and `connection.on`.
97+
98+
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.
99+
100+
101+
## Call hub methods from the client
102+
103+
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.
104+
105+
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:
106+
107+
```swift
108+
// Using invoke, which waits for a response
109+
try await connection.invoke(method: "SendMessage", arguments: "myUser", "Hello")
110+
111+
// Using send, which does not wait for a response
112+
try await connection.send(method: "SendMessage", arguments: "myUser", "Hello")
113+
```
114+
115+
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.
116+
117+
## Logging
118+
119+
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.
120+
121+
### Log level
122+
123+
Use `HubConnectionBuilder().withLogLevel(LogLevel:)` to set the log level. Messages are logged with the specified log level and higher:
124+
125+
* `LogLevel.debug`: Detailed information useful for debugging.
126+
* `LogLevel.information`: General application messages.
127+
* `LogLevel.warning`: Warnings about potential issues.
128+
* `LogLevel.error`: Errors that need immediate attention.
129+
130+
## Client results
131+
132+
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:
133+
134+
```swift
135+
await connection.on("ClientResult") { (message: String) in
136+
return "client response"
137+
}
138+
```
139+
140+
For example, the server can invoke the `ClientResult` method on the client and wait for the returned value:
141+
142+
```csharp
143+
public class ChatHub : Hub
144+
{
145+
public async Task TriggerClientResult()
146+
{
147+
var message = await Clients.Client(connectionId).InvokeAsync<string>("ClientResult");
148+
}
149+
}
150+
```
151+
152+
## Working with streaming responses
153+
154+
To receive a stream of data from the server, use the `stream` method. The method returns a stream that you can iterate over asynchronously:
155+
156+
```swift
157+
let stream: any StreamResult<String> = try await connection.stream(method: "StreamMethod")
158+
for try await item in stream.stream {
159+
print("Received item: \(item)")
160+
}
161+
```
162+
163+
## Handle lost connection
164+
165+
### Automatic reconnect
166+
167+
The SignalR Swift client supports automatic reconnect. To enable it, call withAutomaticReconnect() while building the connection. Automatic reconnect is disabled by default.
168+
169+
```swift
170+
let connection = HubConnectionBuilder()
171+
.withUrl(url: "https://your-signalr-server")
172+
.withAutomaticReconnect()
173+
.build()
174+
```
175+
176+
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.
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+
## Additional resources
220+
221+
* [WebPack and TypeScript tutorial](xref:tutorials/signalr-typescript-webpack)
222+
* [Hubs](xref:signalr/hubs)
223+
* [.NET client](xref:signalr/dotnet-client)
224+
* [JavaScript client](xref:signalr/javascript-client)
225+
* [Publish to Azure](xref:signalr/publish-to-azure-web-app)
226+
* [Cross-Origin Requests (CORS)](xref:security/cors)
227+
* [Azure SignalR Service serverless documentation](/azure/azure-signalr/signalr-concept-serverless-development-config)
228+
* [Troubleshoot connection errors](xref:signalr/troubleshoot)

0 commit comments

Comments
 (0)