In the previous article (http://trikalabs.com/aws-appsync-swift/) we set up AppSync into our app. In this article, we will see how we can add real-time data functionality into our app by using subscribers.
Adding subscriptions is very easy, especially when the amplify has generated the code for us.
All we have to do is create the following code in the ViewController:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
var discard: Cancellable? func startSubscriptionForEvent() throws { do { discard = try appSyncClient?.subscribe(subscription: OnCreateTodoSubscription(), resultHandler: { (result, transaction, error) in if let result = result { print(result.data!.onCreateTodo!.name + " " + result.data!.onCreateTodo!.description!) } else if let error = error { print(error.localizedDescription) } }) } catch { print("Error starting subscription.") } } override func viewDidLoad() { super.viewDidLoad() try? startSubscriptionForEvent() setupAppSync() } |
And let’s put a breakpoint inside the body of the resultHandler closure.
Now let’s go to the AWS console, navigate to AppSync. Select queries and trigger an event:
To execute the query, you have to log in. In order to find the ClientID you have to go to Cognito -> Manage User Pools -> select the user pool -> general settings -> App clients.
If everything is set up correctly the code execution stops at the breakpoint.
At this point we can update our UI, so to keep it in sync with our server data.
Subscribers are very powerful because they are working using web sockets. That means we don’t have to poll for updates or ask the user to pull to refresh to get new data. If we set up subscribers, as soon we have new data the subscribers will be called automatically.