ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

iOS Swift Introduction, Part 1

Updated on March 20, 2018

You’ve got an iOS app idea but don’t know how to get started?

Mobile iOS development is one of Quadion’s main areas of expertise and developing new apps is something we do on a regular basis. Mainly, our team is made up of experienced developers but we also count with the occasional newbie that is taking the first steps in the mobile programming world. If this is your case, you are in the right article!. We will show you the simplest ways of carrying out several common tasks performed in mobile development so you can get a look of what iOS programming is like here at Quadion’s headquarters.

You manage basic programming skills but haven’t adventured into the iOS world yet? By reading this article, you will learn how to start with the basics of app building.

Here you have a list of the first steps that should be taken:

  • Creating a list
  • Requesting data to a remote server
  • Showing this data on a list
  • Passing data between screens.

(Keep in mind you will need a Mac and Xcode 9 installed at least.)

Let’s begin.

Open Xcode and click “Create new Xcode project”

Xcode Prompt
Xcode Prompt

then on “Single View App” and type a name for your new project, in this case our choice is “Introduction”, make sure Language is set to “Swift” and that “Use Core Data”, “Include Unit Tests” and “Include UI Tests” are unchecked.

On the next screen, Xcode will open the project navigator and pre create some files for you. We will focus mainly on ViewController and Main.storyboard.

  • ViewController is the class where the code for the initial screen will be written.
  • Main.storyboard is a file that contains the app UI screens, it will get modified when you need to create or change screens.

Now let’s begin creating the app! Open the Main.storyboard file and click on the only view controller that is on screen. Notice the window at the bottom right corner where many components are displayed, if you see a grid, click on the List-type button at the left of the filter bar to change the display.

Interface builder, Main.storyboard
Interface builder, Main.storyboard

Search the components and select the TableView component and drag it into the ViewController (Make sure to grab the correct TableView component, not TableViewController TableViewCell), now grab the edges of the TableView and drag them so they fit the whole view controller. It should look like this:

Table view
Table view

Then click the Resolve Auto Layout Issues button (triangle between bars) and click on “add missing constraints”, this will tell TableView to get attached to the edges of the ViewController that contains it.

Now click over the TableView and make sure the Attributes Inspector is displayed at your right side, and increase thePrototype Cells property to 1. This will create a TableViewCell in your TableView component.

Add prototype cell
Add prototype cell

Select the TableViewCell component and change the Style property on the Attributes Inspector window to basic, you will notice this will add a default label in the TableViewCell.

Let’s take a break from the storyboard and check the ViewController class and add a reference there to the newly created TableView we added through the interface builder. Click on ViewController file and add the next code just before the viewDidLoad function.

IBOutlet weak var tableView: UITableView!

We just created a property for the ViewController file, that will point to a UITableView component. IBOutlet means that this property will come from the Interface builder.

Now open Main.storyboard select the ViewController and click on the Connections inspector (Right bar), under Outlets it should appear the tableView property we defined earlier on the ViewController file. Now click on the circle and drag the line to the TableView component in the storyboard.

Connecting outlets.
Connecting outlets.

We’ve finally linked the table view in the storyboard to the tableView property on the ViewController file, now let’s begin filling this with data!

Add the following code:

This will create an array with 20 elements that will be desplayed on the TableView. If you run the app right now it will show an empty list, so how do we pass the Strings we have just created to the list?

Introducing UITableViewDataSource and UITableViewDelegate

Add the following code besides the UIViewController declaration:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate{

UITableViewDataSource is a protocol used to tell the TableView object how to construct and modify its view. UITableViewDelegate allows its conforming class to set up the header and footer, reorder items and manage the selection on cells.

After adding this code, Xcode will warn you that ViewController does not conform to protocol UITableViewDataSource, so let’s fix it by adding the following code at the bottom of the file:

1- Tells the TableView how many cells are there in total. Right now there are as many cells as items in the staticDataArray property.

2- Function that returns the TableViewCell that it’s going to be placed at indexPath position.

3- Gets a cell with the specified Identifier that is outside the table view’s bounds so it can be reused if no cell is found to create a new one.

4- Change the text of the cell to match the String in staticDataArray at indexPath.row position.

Finally add the following lines to the bottom of viewDidLoad:

This will tell the tableView who to ask for the data source and delegate implementations.

We are almost done, we just need to set the Identifier we mentioned earlier to the TableViewCell in Main.storyboard, so open up the storyboard, select the TableViewCell (make sure to select the table view cell, and not its content view) and in the Attributes Inspector change the Identifier value to BasicCellIdentifier.

Now let’s run the app and see the results! We can see now that we have a list of 20 elements correctly enumerated! We can scroll up and down and the elements are always in position.

But this is only static data so how do we fill the table view with dynamic data that comes from a remote server?

Enter URLSession

URLSession is a class that coordinates several network transfer tasks. These tasks are defined by the URLSessionTask base class. In this example we will be using URLSessionDataTask to retrieve several public repositories from GitHub.

First let’s create a new class that handles the request for us and in such way keep the code a litte more separate and clean.

Click on File > New > File on the selection manager, choose Swift file and enter RequestManager as name, then click Create. Finally, add the following code:

Ok that’s a lot of code at once, so let’s break it down:

1- Private property that holds the current URLSession.

2- Public function that accepts a closure as a parameter, the closure will act as a kind of Callback function, so we can pass data from this function to the calling object.

3- We create an URLComponentusing the public github endpoint, and protect ourselves from wrong typed urls.

4- Create a new DataTask with the previous created url, and listen for its completion.

5- If the request has an error, print it to console and do nothing else.

6- Check if data is not null and if response returned code 200, also print an error.

7- Execute the completion handler with the returned data.

8- Start the task!

Now that we have a basic RequestManager we need to call the requestPublicGithubRepos from ViewController.

Open ViewController and add the following code at the bottom of viewDidLoad:

And now Run the app.

In the end, “Data 411324 bytes” will appear on the console meaning that our request was successful!. But wait, how do we convert this raw data into something more manageable like an object?

GitHubRepo model

Let´s create a new class called GitHubRepo. To make it work, it should have the following:

1- Two properties: the repository name and the full user/repository name.

2- Constructor for the GitHubRepo class, it accepts a dictionary of String keys and Any type value objects.

3- Retrive the object’s values from the dictionary, if not found add default value.

GitHubRepo class is the base object type which we will create from the Data obtained from the RequestManager. If we check the github endpoint we’ll see that it returns a list of objects in json format:

So now we need to transform that Data object into a list of GitHubRepo. To do that, open the ViewController file and add a new property: var githubRepos = [GitHubRepo]()

Then in the request PublicGithubRepos closure, add the following code:

1- Try and transform the json data into a List of Dictionaries (since this is a list of json objects, and each dictionary represents an object), then save into a local variable.

2- Use the flatMap operator, to transform each element of the list into a GitHubRepo object.

Now that we have stored in memory a list of github repos, we can show these repositories in the list. So, let’s modify the TableViewDataSource functions as it follows:

We just changed the reference to the data from staticDataArray to githubRepos list which will display the repos when we get a response.

We need one final code line before we can run the app, and it goes at the bottom of the requestPublicGithubRepos closure.

1- Run the following block of code in the main thread as it is UI related.

2- Tell the tableView to reload its data. This will trigger a call to the data source methods so that the table view shows the latest info.

Run the app and marvel at the results!

© 2018 Quadion Technologies


    0 of 8192 characters used
    Post Comment

    No comments yet.


    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at:

    Show Details
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the or domains, for performance and efficiency reasons. (Privacy Policy)
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)
    ClickscoThis is a data management platform studying reader behavior (Privacy Policy)