Use GraphQL Subscriptions on iOS :ok_hand:
LiveGQL is a simple library to use GraphQL Subscribtion on WebSocket based on Apollo Protocol.
The Android version is here
We also use SocketRocket and JSONCodable, thanks to them
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '10.0'
use_frameworks!
target '<Your Target Name>' do
pod 'LiveGQL', '~> 2.0.0'
end
github "florianmari/LiveGQL"
See Carthage guide for more informations about integrating with Carthage.
Just copy files in the Source folder!
Important: to not fall out the variable in the scope, please instantiate above your viewDidLoad() for example.
import LiveGQL
let gql = LiveGQL(socket: "ws://localhost:7003/feedback")
gql.delegate = self
gql.initServer(connectionParams: nil, reconnect: true)
You can set a Dictionnary[String:String] as connectionParams like for authentification by example.
The default protocol is now: graphql-subscriptions, but you can specify yours this way
import LiveGQL
let gql = LiveGQL(socket: "ws://localhost:7003/feedback", protocol: "graphql-subscriptions")
Just call subscribe method, set an identifier and your subscription query as well.
gql.subscribe(graphql: "subscription {feedbackAdded {id, text}}", identifier: "feed")
These parameters are mandatory but you can specify exposed variables and operation names if you want, look at the signature:
public func subscribe(graphql query: String, variables: [String: String]?, operationName: String?, identifier: String) {}
You have to implement delegate method, in your main ViewController (for example) just att that
override func viewDidLoad() {
super.viewDidLoad()
gql.delegate = self
// Do any additional setup after loading the view, typically from a nib.
}
Below your class add the folowing extension and implement the method:
extension ViewController: LiveGQLDelegate {
func receivedMessage(text: String) {
print("Received Message: \(text)")
}
}
Just call unsubscribe method and your identifier
gql.unsubscribe(identifier: "feed")
gql.closeConnection()
In this second version of LiveGQL, we give up Starscream for using SocketRocket from Facebook, as well, the protocol has been fixed and you can specify yours!
I’d like to thanks these people for their contributions:
[@rhishikeshj] for cleaning the code and implement SocketRocket!
[@duncsand] for adding exposed variables and operationName on subscription call
[@josefdolezal] for giving us Carthage support!