Basics of iOS Networking – Swift Style

Networking in the mobile context largely entails communicating with external entities over the internet. Like most modern web or mobile platforms today iOS supports HTTP.

These network requests are referred to as ‘Tasks’ in the iOS world and there are three basic network tasks you can perform using the NSURLSession API

Data Tasks – These are network tasks where you exchange simple data which typically get stored in memory as a NSData object during server interactivity

Download Tasks – These tasks involve retrieving the contents of a url as a temporary file from a server (supports running as a background activity)

Upload Tasks – These tasks handle similar messages as the download tasks just in the opposite direction by uploading files to a server (also supports running as a background activity)

This API is asynchronous and provides what some might liken to callbacks in Javascript. The example below is a data task (indicated by ‘dataTaskWithRequest’)

Screen Shot 2016-02-11 at 5.26.25 PM.png

‘in’ signifies the beginning of the completion handler block. This call can’t actually be kicked off without calling resume method on the task

data refers to the actual data you expect back and looks like byte stream data when you get the service response. This needs to be deserialized which you can do like below

Screen Shot 2016-02-11 at 5.21.43 PM.png

response gives you details about your response such as status code and such

error gives you detail if there is an error. If there is none you can expect it to be nil. data is nil if an error is returned

This is not the all in all you need to know on iOS networking but at the very least it should give you a thousand foot view of what you need to know make very common network calls in iOS using Swift.

One last point to note. By default iOS limits regular HTTP calls favoring HTTPS calls out of box. So you need to account for extra steps to support network calls to urls that are prefixed with basic HTTP.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create a free website or blog at WordPress.com.

Up ↑

%d bloggers like this: