Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

iOS Swift Introduction (Part 1)

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

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

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

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

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.

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!

You may be wondering this is all nice and everything but how do we change screens? How do I access a more detailed view of a github repository? We’ll take a shot at these questions on the next article.

Would you like to know more? Do you need our help? Contact Us!
www.quadiontech.com


iOS Swift Introduction (Part 1) was originally published in Quadion Technologies on Medium, where people are continuing the conversation by highlighting and responding to this story.



This post first appeared on Quadion Technologies, please read the originial post: here

Share the post

iOS Swift Introduction (Part 1)

×

Subscribe to Quadion Technologies

Get updates delivered right to your inbox!

Thank you for your subscription

×