6.1 C
Canberra
Tuesday, July 22, 2025

Do you have to use community connectivity checks in Swift? – Donny Wals


Lots of trendy apps have a networking part to them. This could possibly be as a result of your app depends on a server fully for all information, otherwise you’re simply sending a few requests as a again up or to kick off some server aspect processing. When implementing networking, it’s not unusual for builders to verify the community’s availability earlier than making a community request.

The reasoning behind such a verify is that we are able to inform the person that their request will fail earlier than we even try and make the request.

Sound like good UX, proper?

The query is whether or not it actually is sweet UX. On this weblog submit I’d prefer to discover a few of the professionals and cons {that a} person may run into while you implement a community connectivity verify with, for instance, NWPathMonitor.

A person’s connection can change at any time

Nothing is as prone to vary as a person’s community connection. One second they is perhaps on WiFi, the following they’re in an elevator with no connection, and simply moments later they’ll be on a quick 5G connection solely to modify to a a lot slower connection when their prepare enters an enormous tunnel.

In the event you’re stopping a person from initiating a community name once they momentarily don’t have a connection, that may appear extraordinarily bizarre to them. By the point your alert exhibits as much as inform them there’s no connection, they may have already restored connection. And by the point the precise community name will get made the elevator door shut and … the community name nonetheless fails because of the person not being related to the web.

As a consequence of altering situations, it’s typically really helpful that apps try a community name, whatever the person’s connection standing. In spite of everything, the standing can change at any time. So when you may have the ability to efficiently kick off a community name, there’s no assure you’re capable of end the decision.

A significantly better person expertise is to only attempt the community name. If the decision fails attributable to a scarcity of web connection, URLSession will inform you about it, and you may inform the person accordingly.

Talking of URLSession… there are a number of methods by which URLSession will assist us deal with offline utilization of our app.

You may need a cached response

In case your app is used ceaselessly, and it shows comparatively static information, it’s doubtless that your server will embrace cache headers the place acceptable. It will permit URLSession to domestically cache responses for sure requests which implies that you don’t must go to the server for these particular requests.

Because of this, when configured accurately, URLSession can serve sure requests with out an web connection.

After all, that implies that the person will need to have visited a particular URL earlier than, and the server should embrace the suitable cache headers in its response however when that’s all arrange accurately, URLSession will serve cached responses robotically with out even letting you, the developer, know.

Your person is perhaps offline and a lot of the app nonetheless works positive with none work out of your finish.

It will solely work for requests the place the person fetches information from the server so actions like submitting a remark or making a purchase order in your app gained’t work, however that’s no purpose to begin placing checks in place earlier than sending a POST request.

As I discussed within the earlier part, the connection standing can change at any time, and if URLSession wasn’t capable of make the request it is going to inform you about it.

For conditions the place your person tries to provoke a request when there’s no lively connection (but) URLSession has one other trick up its sleeve; automated retries.

URLSession can retry community calls robotically upon reconnecting

Typically your person will provoke actions that may stay related for a short while. Or, in different phrases, the person will do one thing (like sending an electronic mail) the place it’s fully positive if URLSession can’t make the request now and as a substitute makes the request as quickly because the person is again on-line.

To allow this conduct you will need to set the waitsForConnectivity in your URLSession’s configuration to true:

class APIClient {
  let session: URLSession

  init() {
    let config = URLSessionConfiguration.default
    config.waitsForConnectivity = true

    self.session = URLSession(configuration: config)
  }

  func loadInformation() async throws -> Info {
    let (information, response) = attempt await session.information(from: someURL)
    // ...
  }

Within the code above, I’ve created my very own URLSession occasion that’s configured to attend for connectivity if we try and make a community name when there’s no community out there. At any time when I make a request by this session whereas offline, the request won’t fail instantly. As a substitute, it stays pending till a community connection is established.

By default, the wait time for connectivity is a number of days. You may change this to a extra cheap quantity like 60 seconds by setting timeoutIntervalForResource:

init() {
  let config = URLSessionConfiguration.default
  config.waitsForConnectivity = true
  config.timeoutIntervalForResource = 60

  self.session = URLSession(configuration: config)
}

That approach a request will stay pending for 60 seconds earlier than giving up and failing with a community error.

If you wish to have some logic in your app to detect when URLSession is ready for connectivity, you possibly can implement a URLSessionTaskDelegate. The delegate’s urlSession(_:taskIsWaitingForConnectivity:) methodology will likely be known as each time a job is unable to make a request instantly.

Be aware that ready for connectivity gained’t retry the request if the connection drops in the course of an information switch. This feature solely applies to ready for a connection to begin the request.

In abstract

Dealing with offline situations ought to be a major concern for cell builders. A person’s connection standing can change rapidly, and ceaselessly. Some builders will “preflight” their requests and verify whether or not a connection is out there earlier than making an attempt to make a request as a way to save a person’s time and sources.

The main draw back of doing that is that having a connection proper earlier than making a request doesn’t imply the connection is there when the request really begins, and it doesn’t imply the connection will likely be there for your complete period of the request.

The really helpful strategy is to only go forward and make the request and to deal with offline situations if / when a community name fails.

URLSession has built-in mechanisms like a cache and the power to attend for connections to offer information (if attainable) when the person is offline, and it additionally has the built-in capability to take a request, await a connection to be out there, after which begin the request robotically.

The system does a fairly good job of serving to us assist and deal with offline situations in our apps, which implies that checking for connections with utilities like NWPathMonitor normally finally ends up doing extra hurt than good.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

[td_block_social_counter facebook="tagdiv" twitter="tagdivofficial" youtube="tagdiv" style="style8 td-social-boxed td-social-font-icons" tdc_css="eyJhbGwiOnsibWFyZ2luLWJvdHRvbSI6IjM4IiwiZGlzcGxheSI6IiJ9LCJwb3J0cmFpdCI6eyJtYXJnaW4tYm90dG9tIjoiMzAiLCJkaXNwbGF5IjoiIn0sInBvcnRyYWl0X21heF93aWR0aCI6MTAxOCwicG9ydHJhaXRfbWluX3dpZHRoIjo3Njh9" custom_title="Stay Connected" block_template_id="td_block_template_8" f_header_font_family="712" f_header_font_transform="uppercase" f_header_font_weight="500" f_header_font_size="17" border_color="#dd3333"]
- Advertisement -spot_img

Latest Articles