Jonathan Bouchard
Jonathan Bouchard

Reputation: 443

How to read HTTP requests without flooding my API with Swift 3

I'm trying to make a simple messaging app using an API. Right now, I have a thread that checks a request each second and see if the number of messages have changed, but this causes so much trouble, the RAM is constantly going up and the API becomes unresponsive because of 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 fine, I can send messages and see messages sent to me (with a decent delay), but my logic with the request at every 2 second is way off and I acknowledge it. I'm still learning Swift so I'd really appreciate some advises on this matter, thanks!

Upvotes: 3

Views: 140

Answers (1)

Aleksandr Medvedev
Aleksandr Medvedev

Reputation: 8978

In comments you provide elaboration, saying that you are implementing a messenger. For that purpose simple HTTP requests are not appropriate approach. Instead, you want to introduce so-called socket connection. I dare quote myself from another relevant thread:

It's called socket-connections, at a glance it looks like a channel, that hosts on a server side, and any clients (devices) can join this channel (two or more, whatever you want). If device send a message to the server, it should broadcast the message toward all other participants (it can broadcast the message even to the sender itself, but with some meta-information so we can distiguish our own messages and ignore them).

Thereby first of all you need server with socket connection established, then you can implement any of already existing solutions (e.g. https://github.com/daltoniam/Starscream for iOS). Also you may want to take a look at AWS https://aws.amazon.com, as it has the socket connection service out of the box for the server side and required SDK for both Android and iOS platforms.

Upvotes: 1

Related Questions