Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save mohammadsadra/ce714ebc663803b20e5593b7071b1f1d to your computer and use it in GitHub Desktop.

Select an option

Save mohammadsadra/ce714ebc663803b20e5593b7071b1f1d to your computer and use it in GitHub Desktop.
use_frameworks!
pod 'SwiftSignalRClient'
let hubConnection = HubConnectionBuilder(url: URL(string: "http://localhost:5000/playground")!)
.withLogging(minLogLevel: .debug)
.build()
public protocol HubConnectionDelegate: class {
func connectionDidOpen(hubConnection: HubConnection)
func connectionDidFailToOpen(error: Error)
func connectionDidClose(error: Error?)
}
// invoking a hub method and receiving a result
hubConnection.invoke(method: "Add", 2, 3, resultType: Int.self) { result, error in
if let error = error {
print("error: \(error)")
} else {
print("Add result: \(result!)")
}
}
// invoking a hub method that does not return a result
hubConnection.invoke(method: "Broadcast", "Playground user", "Sending a message") { error in
if let error = error {
print("error: \(error)")
} else {
print("Broadcast invocation completed without errors")
}
}
hubConnection.invoke(method: "Add", arguments: [2, 3], resultType: Int.self) { result, error in
if let error = error {
print("error: \(error)")
} else {
print("Add result: \(result!)")
}
}
hubConnection.on(method: "AddMessage") {(user: String, message: String) in
print(">>> \(user): \(message)")
}
hubConnection.on(method: "AddMessage", callback: { argumentExtractor in
let user = try argumentExtractor.getArgument(type: String.self)
var message = ""
if argumentExtractor.hasMoreArgs() {
message = try argumentExtractor.getArgument(type: String.self)
}
print(">>> \(user): \(message)")
})
hubConnection.send(method: "Broadcast", "Playground user", "Testing send") { error in
if let error = error {
print("Send failed: \(error)")
}
}
hubConnection.start()
hubConnection.stop()
let streamHandle = hubConnection.stream(method: "StreamNumbers", 1, 10000, itemType: Int.self,
streamItemReceived: { item in print(">>> \(item!)") }) { error in
print("Stream closed.")
if let error = error {
print("Error: \(error)")
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2)) {
hubConnection.cancelStreamInvocation(streamHandle: streamHandle) { error in
print("Canceling stream invocation failed: \(error)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment