How to read HTTP requests without flooding my API using Swift 3
I am trying to create a simple messaging application using API. Right now, I have a thread that checks the request every second and sees if the number of messages has changed, but this causes so many problems that the RAM is constantly growing and the API becomes unresponsive due to the large number of requests. At the moment my code looks like this:
var request = URLRequest(url: URL(string: "URL")!)
let session = URLSession.shared
public func thread()
{
DispatchQueue.global(qos: .background).async {
while(true)
{
self.request.httpMethod = "GET"
self.session.dataTask(with: self.request) {data, response, err in
let json = try! JSONSerialization.jsonObject(with: data!, options: []) as? [String: Any]
let data = json?["data"] as? [[String: Any]]
if((data?.count)! > self.nbMessages)
{
self.messages.removeAll()
for message in data! {
let text = message["message_body"] as? String
let creator = message["creator_id"] as? Int
self.messages.append([text!, String(creator!)])
}
DispatchQueue.main.async {
self.nbMessages = (data?.count)!
self.TableView.reloadData()
let scrollPoint = CGPoint(x: 0, y: self.TableView.contentSize.height - self.TableView.frame.size.height)
self.TableView.setContentOffset(scrollPoint, animated: false)
}
}
}.resume()
usleep(2000)
}
}
}
This works great, I can send messages and see messages sent to me (with a decent delay), but my logic with a request every two seconds goes away and I admit it. I'm still involved with Swift, so I really appreciate some advice on this, thanks!
source to share
In the comments, you provide clarification by saying that you are implementing a messenger. Simple HTTP requests are not suitable for this. Instead, you want to introduce a so-called socket connection. I dare to quote myself from another relevant thread :
It is called socket connections, at first glance it looks like a pipe that is hosted on the server side, and any clients (devices) can join this pipe (two or more, whatever you want). If the device sends a message to the server, it must broadcast the message to all other participants (it can broadcast the message even to the sender himself, but with some meta information so that we can distinguish our own messages and ignore them).
So first of all you need a server with an established socket connection, then you can implement any of the already existing solutions (for example, https://github.com/daltoniam/Starscream for IOS). You can also take a look at AWS https://aws.amazon.com as it has a socket service to connect to the server and requires an SDK for Android and iOS platforms.
source to share