Functions in a remote interface are just regular functions in Swift that, when connected to a Web Frame, can be invoked from the web layer.
Examples
Functions can be declared any number of ways. The following examples are for a remote function that responds with the data that is sent to it from the web layer.
Declared as a function
func echo(call: Call) {
call.respond(with: call.request.data)
}
Declared as a method within a class
class Echo {
func echo(call: Call) {
call.respond(with: call.request.data)
}
}
Declared as a lambda
functions: [
"echo": { call in
call.respond(with: call.request.data)
}
],
Web Frame Configuration
For the following example, we’ll be using a function declared like the following:
func echo(call: Call) {
call.respond(with: call.request.data)
}
Since functions have first-class support in Swift, we can pass them as references to the Web Frame configuration.
let configuration = WebFrame.Configuration(
baseURL: ...
functions: [
"echo": echo,
],
observables: [:]
)
Peregrine expects remote functions to match the following type in Swift.
typealias RemoteFunction = (_: Call) -> Void
iOS API
Call
An instance of the Call
class represents a single invocation of a remote
function.
Properties
let request: Request
The Request
instance associated with this call.
Methods
func respond()
Complete the call by responding with empty data.
func respond(with text: String)
Complete the call by responding with a UTF-8 encoded string.
func respond(with data: Data)
Complete the call by responding with arbitrary data.
func respond<T: Encodable>(with json: T) throws
Complete the call by responding with an encodable object.
Structs (or classes) must implement the
Encodable
protocol
from Swift:
struct SizeResponse: Encodable {
let width: Double
let height: Double
}
Then, objects can be passed to .respond()
directly:
call.respond(with: SizeResponse(width: 100, height: 100))
This function will throw an error if encoding fails (highly unlikely).
Not all Events must be wrapped in objects. In Swift, many data types implement the Encodable protocol: strings, booleans, ints, doubles, arrays, dictionaries, etc.
func fail(_ message: String?, code: String? = nil)
Complete the call (marking it as failed) by responding with an error message and code.
This will cause the web client to throw a ClientError
exception.
Request
Contains the request data from the web layer and helpers to extract it.
Properties
let data: Data
The raw data from the web layer.
let text: String
The data decoded as a UTF-8 string.
Methods
func json<T: Decodable>(_ type: T.Type) throws -> T
The data converted to a decodable object.
Structs (or classes) must implement the
Decodable
protocol
from Swift:
struct SizeRequest: Decodable {
let name: String
}
Then, pass the type to .json()
:
let sizeRequest = try call.request.json(SizeRequest.self)
let shapeName = sizeRequest.name
This function will throw an error if decoding fails.