SwiftUI and Nodejs communication
Most of us use rest api connection with backend and this way goes single way. I mean, this connection communicates one-way direction. so I wanna talk about this article about how we can connect with the backend. In this article we use nodejs as backend, cause node js is simple to use. We will make a reel world application in this article, make communicate swift and node js socket-io. Our app connect local socket server and listen to it on the fetched-currency-list channel. If get any response on the channel reloads the list again. Every minute app keeps trying to fetch for new list from the server. The server listens to the app on get-new-currency-list If get any requests, return a new list to the app. The app will look like this
Let's go…
Installing node js (Skip this step If you installed)
You can download it here and set it up on your computer quickly
Make sure you install and are ready to use node js on your computer, open your terminal write the below code. If you don’t get any error, node js is ready.
- Setup application
To create SwiftUI app, choose the app and set a name
Set Interface SwiftUI
We will use Socket.IO-Client-Swift to connect the socket server using cocopods . On the main folder run the below code to setup podfile
After replacing Podfile with this
And run it
The App side is ready to code now!
2. Setup server
To create a socket server run the below code on the desktop(or what folder inside you want)
Replace your package.js with this
To install dependencies
Server-side is ready to coding too!
3. Let build our app
We will use coinmarketcap data to fetch currencies. Don’t forget to get your API key on here
Coinmarketcap has a rate limit. This limit scales with the usage tier and resets every 60 seconds.
From the server-side put the below code in index.js
With this code, we made a socket connection and open a public channel on our local (localhost:5000). We make a connection to this local connection and listen to events.
With below response model will use socket response.
For our app UI, you can use the below code, this code makes a connection with the local server and communicates it. With fetched-currency-list listening, any event on this If get any event, parse the response and show on the screen. Every minute we send a new list request from the server on get-new-currency-list.
- We create a socket connection
- Listening socket connection
- Parsing received a response from the socket connection
- Sending new list request to connection every minute
- Parsing currency variable with number formatter
Finally, we made two-way communication using Swift and Nodejs. Hope you learn something. If you have any questions you can ask me any time on twitter.
Source Code