测试已测试 | ✗ |
语言语言 | SwiftSwift |
许可证 | MIT |
发布上次发布 | 2017 年 9 月 |
SwiftSwift 版本 | 3.0 |
SPM支持 SPM | ✗ |
由 Adam Hartford 维护。
SignalR 的 Swift 客户端。支持中心和持久连接。
我已发布了一个示例 SignalR 服务器在 http://swiftr.azurewebsites.net。当前的 iOS 演示应用程序现在使用此服务器。请查看 SwiftRChat 获取源代码。它是基于这个的,有一些小的变化
http://www.asp.net/signalr/overview/deployment/using-signalr-with-azure-web-sites
它是在隐藏的网页视图中运行的 SignalR JavaScript 客户端的包装。因此,它受该客户端相同的限制——即在使用 WebSocket 时没有对自定义标头的支持。这是因为浏览器的 WebSocket 客户端不支持自定义标头。
随便,您的选择。请注意,由于 WKWebView 在单独的进程中运行,它无法访问 NSHTTPCookieStorage 中的 Cookie。如果您需要 Cookie,请使用 UIWebView。SwiftR 默认使用 UIWebView,但您可以选择使用 WKWebView
// Client
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.useWKWebView = true
此外,在使用 WKWebView 时,请确保在您的服务器上启用 CORS
// Server
app.UseCors (CorsOptions.AllowAll);
// See my SignalRApplication repo for a CORS example with ASP.NET Core.
SwiftR 支持 SignalR 版本 2.x。默认假定为 2.2.1。要更改 SignalR 的版本
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.signalRVersion = .v2_2_1
//connection.signalRVersion = .v2_2_0
//connection.signalRVersion = .v2_1_2
//connection.signalRVersion = .v2_1_1
//connection.signalRVersion = .v2_1_0
//connection.signalRVersion = .v2_0_3
//connection.signalRVersion = .v2_0_2
//connection.signalRVersion = .v2_0_1
//connection.signalRVersion = .v2_0_0
CocoaPods
use_frameworks!
pod 'SwiftR'
Carthage
github 'adamhartford/SwiftR'
请参阅 https://github.com/adamhartford/SignalRDemo 以获取示例自托管的 SignalR 应用程序。或者,查看 https://github.com/adamhartford/SignalRApplication 中的 ASP.NET 5 版本。
// Server
public class SimpleHub : Hub
{
public void SendSimple(string message, string detail)
{
Clients.All.notifySimple (message, detail);
}
}
回调响应中的默认参数名称
// Client
let connection = SignalR("https://:5000")
let simpleHub = Hub("simpleHub")
simpleHub.on("notifySimple") { args in
let message = args![0] as! String
let detail = args![1] as! String
print("Message: \(message)\nDetail: \(detail)")
}
connection.addHub(simpleHub)
connection.start()
...
// Invoke server method
simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"])
// Invoke server method and handle response
simpleHub.invoke("sendSimple", arguments: ["Simple Test", "This is a simple message"]) { (result, error) in
if let e = error {
print("Error: \(e)")
} else {
print("Success!")
if let r = result {
print("Result: \(r)")
}
}
}
// Server
public class ComplexMessage
{
public int MessageId { get; set; }
public string Message { get; set; }
public string Detail { get; set; }
public IEnumerable<String> Items { get; set; }
}
// Server
public class ComplexHub : Hub
{
public void SendComplex(ComplexMessage message)
{
Clients.All.notifyComplex (message);
}
}
// Client
let connection = SignalR("https://:5000")
let complexHub = Hub("complexHub")
complexHub.on("notifyComplex") { args in
let m: AnyObject = args![0] as AnyObject!
print(m)
}
connection.addHub(complexHub)
connection.start()
...
let message = [
"messageId": 1,
"message": "Complex Test",
"detail": "This is a complex message",
"items": ["foo", "bar", "baz"]
]
// Invoke server method
complexHub.invoke("sendComplex", parameters: [message])
// Server
app.MapSignalR<MyConnection> ("/echo");
...
public class MyConnection : PersistentConnection
{
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Connection.Broadcast(data);
}
}
// Client
let persistentConnection = SignalR("https://:8080/echo", connectionType: .persistent)
persistentConnection.received = { data in
print(data)
}
persistentConnection.start()
// Send data
persistentConnection.send("Persistent Connection Test")
默认情况下,SignalR会选择对您最佳的传输方式。您还可以指定传输方法
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.transport = .auto // This is the default
connection.transport = .webSockets
connection.transport = .serverSentEvents
connection.transport = .foreverFrame
connection.transport = .longPolling
SwiftR公开了以下SignalR事件
let connection = SignalR("http://swiftr.azurewebsites.net")
connection.started = { print("started") }
connection.connected = { print("connected: \(connection.connectionID)") }
connection.connectionSlow = { print("connectionSlow") }
connection.reconnecting = { print("reconnecting") }
connection.reconnected = { print("reconnected") }
connection.disconnected = { print("disconnected") }
connection.start()
您可能会发现,一旦断开连接,手动尝试重新连接是必要的。以下是如何操作的示例
connection.disconnected = {
print("Disconnected...")
// Try again after 5 seconds
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(5 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
connection.start()
}
}
使用stop()
和start()
方法手动管理连接。
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.start()
connection.stop()
...
if connection.state == .connected {
connection.stop()
} else if connection.state == .disonnected {
connection.start()
}
public enum State {
case connecting
case connected
case disconnected
}
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.queryString = ["foo": "bar"]
let connection = SignalR("https://swiftr.azurewebsites.net")
connection.headers = ["X-MyHeader1": "Value1", "X-MyHeader2", "Value2"]
SwiftR会将您的应用中的NSHTTPCookieStorage中的任何cookie发送到SignalR。您也可以手动设置cookie
let cookieProperties = [
NSHTTPCookieName: "Foo",
NSHTTPCookieValue: "Bar",
NSHTTPCookieDomain: "myserver.com",
NSHTTPCookiePath: "/",
]
let cookie = NSHTTPCookie(properties: cookieProperties)
NSHTTPCookieStorage.sharedHTTPCookieStorage().setCookie(cookie!)
connection.error = { error in
print("Error: \(error)")
if let source = error?["source"] as? String, source == "TimeoutException" {
print("Connection timed out. Restarting...")
connection.start()
}
}
SwiftR遵循MIT许可证发布。详细信息请参阅LICENSE。