Swift Tutorial – Developing iOS Apps Part 1

Swift Tutorial

iOS Development moves to Swift

This tutorial updated to reflect changes in Xcode 8.3.1 and iOS 10, as of April 17, 2017

Apple announced at WWDC a major change to the way iOS apps are developed, it can now be done using a new programming language called Swift. In my efforts to adapt and learn the language’s common patterns and best practices, I will be posting regularly as I step through the learning process, sharing everything I find. I hope you decide to follow along!

In this tutorial we will build an iOS application that will pull down iTunes tracks from the iTunes web API (or application programming interface), display that information on the iPhone using a common UI element called a Table View, and finally allow us to drill down in to an album and play some of the tracks. If you are looking to develop your website further hire professional web development services, to help you.

Tutorial Index

So I’m going to start with a pretty basic app and explain how the code works. Ready? Here we go…

The Basics

Swift opts to use a Javascript-like ‘var’ keyword to define any new variable.

So for example to create a new variable with a bit of text in it, you would have this:

var myString = "This is my string."

This is declared with a var so the variable can change at any time, similar to most languages.

However the let keyword creates constants. These can not ever be changed once they are defined. If you try, a compiler error will appear and the program just won’t run.

let someConstant = 40

In this case kSomeConstant is implicitly defined as an integer, or Int. If you want to be more specific you can specify which type it is like so:

let someOtherConstant: Int = 40

With both arrays and dictionaries, they are described using brackets []

var colorsArray = ["Blue", "Red", "Green", "Yellow"]
var colorsDictionary = ["PrimaryColor":"Green", "SecondaryColor":"Red"]

You can access the members of an array with integer value indexes, and the members of a dictionary with String keys (or other types, but that’ll come in later tutorials)

let firstColor = colorsArray[0]
// firstColor is now "Blue"
let aColor = colorsDictionary["PrimaryColor"]
// aColor is now "Green"

There’s a lot more to go over, but I think these basics are important to get a start going on to the tutorial. So with that, let’s move on to Hello World. If you want to play around with this a bit yourself before getting going on our first iPhone App. Be sure to check out the Playground containing this sample code on Github.

Hello World

Hello World in Swift and iOS

First, we’re going to write the simplest app imaginable to get started, Hello World. This segment comes directly from my upcoming book on Swift development, but it’s so important and fundamental to getting started I thought it would be good to release for free here.

Our app will only do one thing: print “Hello World” to the console. You’ll need a developer copy of Xcode in order to follow along, which requires a developer account. If you have one, head on over to http://developer.apple.com and get your copy before we begin.

So now you’ve got your IDE set up. Let’s write hello world out to the console. This example demonstrates the simplest app that can be built, and more importantly shows that you’re environment is set up correctly.

Set up an Xcode project using the single-view application template, and make sure you opt for Swift as the language.

You should now find an AppDelegate.swift file in the project hierarchy. Inside of this file find the line that says:

"// Override point for customization after application launch."

Replace this line with our amazing hello world code:

print("Hello World")

Hello World Swift Code

Now press run and you should see a blank app boot up, and the words “Hello World” print to the console.
Note that this will not show up in the iPhone simulator. Look at the bottom of your Xcode window and you’ll see a console that says ‘Hello World!’.

Hello World Output

Congratulations! You just wrote your first app in Swift! This app probably won’t win any awards, let’s trying doing something a little deeper…

Adding a Table View

In this section, we’re going to actually put some stuff on the screen.
Open up your Main.storyboard file in Xcode and lets drag in a “Table View” object from the Object Library (don’t use a table view controller.) Position this fullscreen in your app window and make sure it lines up with the edges. Then resize the height by dragging down the top edge and giving a little bit of space (this gives room for the status bar at the top of the phone.) If you run the app at this point, you should see an empty table view in the simulator.

UITableView drag on to StoryBoard

The empty table view in the iPhone Simulator:

The empty table view in the iPhone Simulator

Now we need to set up a delegate and data source for the table view. The Data Source is an object that informs the Table View of which data to show. The delegate let’s us handle interactions such as tapping a row on the Table View.

Setting these outlets is easy to do in interface builder. Just hold control, and then click and drag from the tableview to the “View Controller” object in your storyboard’s hierarchy, and select ‘data source’. Repeat with the ‘delegate’ options.

Setting up the UITableView Data Source and Delegates

I’ve received a ton of questions about this, and many people reporting errors about the table view not being set, so to make things a little easier I made a quick video showing how connecting Storyboard objects to your code works. Make sure to go fullscreen and select the 720p option to make sure you can see what’s happening. This will look slightly different from the Xcode interface you are using, but functionally all this works the same.

Connecting Storyboard Objects to Code in Xcode

Okay, now let’s dig in to the protocol methods for Table Views. Because we’re using the UITableViewDataSource and UITableViewDelegate in our view controller, we need to modify the class definition to say as much.

So open ViewController.swift and modify this line:

class ViewController: UIViewController {

to this:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

This will cause some errors to pop up, but don’t worry this is expected. In fact, the errors are the primary purpose of indicating these protocols on our class. It lets us know that we aren’t done actually implementing the UITableViewDataSource or the UITableViewDelegate yet.

Command+clicking on either of these protocols will show the required functions at the very top. In the case of a tableview dataSource, we need at least these two:

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell


So let’s modify our View Controller class by adding these two functions.

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "MyTestCell")
    cell.textLabel?.text = "Row \(indexPath.row)"
    cell.detailTextLabel?.text = "Subtitle \(indexPath.row)"
    return cell


As a handy trick, when you need to write these long methods for cases like this, you can just start typing the function in Xcode, focusing on the unique part of the name such as “cellForRo…” and Xcode will usually auto-complete what you were typing.

The first method is asking for the number of rows in our section, in this simple tutorial we just hard-code 10, but normally it would be the length of an array controller. This example is intentionally simple.

The second method is where the magic happens. Here we create a new instance of a UITableViewCell called cell, using the Subtitle cell style.
Then, we assign the text value of this cell to the string “Row #(indexPath.row)”
In Swift, this is how variables are embedded within a string. What we’re doing is retrieving the value of indexPath.row by inserting (indexPath.row) in to our string, and dynamically replacing it with the row number of the cell. This allows results such as “Row #1″, “Row #2″, etc.

The detail text label is only available in the Subtitle cell class, which we are using here. We set it similarly to “Subtitle #1″, “Subtitle #2″, and so on.

Go ahead and run your app and you’ll now see an amazing list of cells with titles and subtitles indicating their row numbers. Don’t see the cells? Make sure you connected your storyboard delegate and data source to the ViewController class. See the Youtube video here

This is one of the most common ways to display data in iOS, and will be sure to serve you well. For the full code to my View Controller file, take a look at the full source for this section on github.

You’re doing great!

Made it this far and everything is working? Awesome! If not, let me know if you got stuck. I’m happy to help 🙂

In my Swift book we spend some more time going over the basics, as well as delving much deeper in to the advanced details. Learn more about it here.

In part 2, we’re going to explore using the iTunes search API to create an app capable of finding and displaying albums within the iTunes store.

Full code for this part here »

Go To Part 2 »

Get The Source
Next Part

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS

Using open source iPhone app components with Cocoa Pods

For a while after the initial release of the iPhone App Store and it’s SDK, there was not much in terms of open source code to use and learn from, you can buy iPhone and take advantage of exclusive prime products. But times have changed, and these days there is a huge database of open source components, and even full projects ripe for use in your next app.

This post is a bit of an instructional guide for those looking to take advantage of open source in their iPhone projects. Whether you are new to iOS, a seasoned developer, or a project manager, you can benefit from this short guide.

Currently, the biggest repository of open source iOS components is CocoaPods. The official list of components, known as “Pods’, is maintained in a Github repository located here: https://github.com/CocoaPods/Specs

Unfortunately this list is not particularly easy to browse. To find out the details of any one Pod, you have to select one from the list, pick a version, open the.podspec file, and then pick out the description in the file. Fortunately for you, the handsome reader, you can browse a (possibly slightly out of date) list of these Pods on the site https://www.cocoacontrols.com/cocoapods, in a much more easy to digest format.

So how do you use these? If you’ve got a ruby install set up with ruby gems, you can just navigate to your project directory and create a Podfile file, with no extension. It looks like this:

platform :ios, ‘6.0’

pod ‘TestFlightSDK’, ‘>= 1.1’
pod ‘SVProgressHUD’
pod ‘iRate’
pod ‘TimesSquare’, ‘1.0.1’
pod ‘AFNetworking’, ‘1.1.0’
pod ‘iCarousel’

Once you’ve created this Podfile you can run this command in Terminal:

$ pod install

If it gives you some kind of error, you might need to install Cocoa Pods. If that’s the case you first need to run this:

$ gem install cocoapods

And if that doesn’t work, then you still need ruby gems, and maybe even ruby.

Once you generate the pod install, make sure you close your Xcode project if you already have it open, and from now on use the .xcworkspace file when working on your project. What you’ll find is that Cocoa Pods has now created a subproject for your Pods. Yay! This means you can now compile your dependencies separately from the project, and changes to your project shouldn’t call for a full recompile. More importantly, you can easily update your dependencies by just modifying your Podfile, and running ‘pod install’ again.

So to recap:

1. Install ruby

$ \curl -sSL https://get.rvm.io | bash -s stable

2. Install ruby gems if you don’t have ut

Visit http://rubygems.org/pages/download

3. Install cocoapods

$ gem install cocoapods

4. Create a Podfile in your Xcode project directory

5. Add any relevant pods you might want to use. At this stage I do not specify a version, I let it use the most recent, and then lock it to that version to avoid unwanted updates. I’ll later remove the version specification when I feel it is time to get everything up to date.

6. Run pod install

$ pod install

7. Open your project from the xcworkspace file instead of the xcodeproj file.

8. Enjoy!

Related article: 8 Great Open Source Projects to use in your next iPhone App

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS

The lazy app developer’s way to ship more code

With these three quick tips, you’ll be on your way to being more productive when developing your mobile apps. These are not extremely difficult technical challenges, and should be easy to implement in to your workflow.


Dependency Management

If you’re on iOS, Cocoapods is a godsend. If you’ve ever used bundler with Ruby on Rails, you’ll be familiar with this concept. A series of dependencies for your iOS app are listed out in a human readable format in a Podfile, which is then used with the ‘pod’ command line utility to download, update, install, and check frameworks for compatibility. In the old days iOS developer’s would have to manually manage the importing and linking of every library used, but now cocoapods does the heavy lifting for you. If you’re not using it yet, go check it out. Cocoapods will help you leverage more open source code, more effectively, in less time.

Automated testing

One of the most time consuming parts of developing an iOS app can be performing tests of your application using the device (or iPhone simulator.) But many of the tests you are performing can be partially implemented using the now-default OCUnit testing suite. OCUnit does some nice things, but to truly automate all your actual use testing, look in to Calabash. It’s basically cucumber for iOS, and allows for UI-based testing of apps. By writing proper tests, you can automate almost all testing, find bugs faster, and resolve UI issues before they become serious problems. Not only does automated testing speed up the process of development, but it enables you to ship higher quality code.

Design before you build

I mean this on multiple levels. First, before you begin writing any code, it is a good idea to have a solid concept for your app, along with all the needed features for marketing and promotion.

Second, designing your UI up front can save you a LOT of time and frustration during the development process. Changing the way a button behaves in a Photoshop file after thinking about it a bit, is *much* easier than trying to change it after code has been implemented. Be as certain as possible of your UI before committing any code.

Third, before you (or your programmers) move in to the actual code, it’s important to plan out how every object should exist, and how they should relate to each other. This is basic software planning, but I’ve seen it skipped too many times to not bring it up. Taking this basic step ahead of time can be the difference between a project that completely misses it’s schedule, and a project that is delivered under budget and ahead of time.


Related article: Top 10 Lessons Learned from Launching iPhone Apps

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS

5 things I wish I knew when I released my first iPhone app

I’ve been writing mobile apps for roughly 4 years. I’ve seen dozens of apps come from concept to completion, and I’ve learned many lessons along the way. Here are the top 5 things I wish I knew when I first started out making iOS apps.

Ready? Let’s go!

1. Your icon and name will make or break your app.

You heard it here first. The most critical factor of your app’s success is not your beautiful algorithms, your revolutionary ideas, or even a great marketing campaign to drive initial customers. You could also find a local web developer to help you. No, the most important factor is the icon, and the name. This is all most of your prospective customers see before making the decision to learn more. I’ve been able to measure this first hand by using two different icons and names for two otherwise identical apps, and I’ve repeated the experiment several times. I can say without a doubt that this is the most critical factor to getting downloads. In my last experiment, the app with a brighter and louder icon results in an average of 263 downloads per day, while an identical app with a softer and more toned down icon results in only 2 downloads per day. Wow.

2. Apple provides no way to keep in touch with customers.

So what happens after you get your first 10,000 downloads? What if you want to create a spin-off app leveraging your existing audience, or offer new products within your app? Well, you can always introduce an update, but who knows if your customers will actually download and run it. Furthermore, maybe they have already deleted your app? Previous behavior is the greatest indicator of future behavior, and the previous behavior of your customers is that they *bought something from you*. If you want to grow your audience and generate more revenue from your apps, it is critical that you offer a way to keep in touch with your customers. Set up a Mailchimp list, have them subscribe for push notifications, or have them make an account. Whatever route makes the most sense for your product, just make sure you have a way to keep in touch. You will be glad you did on your next app launch. Apple does none of this for you, they don’t even provide emails or names of the people who purchased your app, so this one is on you!

3. Apps that are too simple will be rejected.

Apple has a lot of rules concerning what is “fit” for the App Store, and what isn’t. One of the most difficult to resolve is an app being “too simple” by Apple’s standards. They are very directly telling you to go spend more money and bloat up your app with features you didn’t think were necessary. So what do you do? Well, my advice is to make sure you are not making an app that only does one simple thing. This is something that needs to be resolved before any development begins, or else you may be faced with a product that you simply can’t release.

4. The app store is not the gold rush it’s touted to be.

There is certainly money to be made on the app store, but don’t expect to publish your first app and rake in millions of dollars in free money. Making a successful app takes a lot of time, money, and great intuition about what people are going to like. Be reasonable with your approach in producing apps, and don’t bet the farm on a single strategy. Even if you are working with only a single app, you should make sure you have other distribution mechanisms outside of simply being on the app store.

5. Analytics are crucial.

Without some basic analytics, you will quickly find yourself wishing you knew some things about your users. This will probably hit you immediately after publishing your app. How many users are using the app? If you don’t implement analytics, all you will get are your daily iTunes sales figures, and I know we’re all more OCD about what’s going on than that. This is your baby after all. Take the time to invest in integrating a good analytics platform. There are some decent free options out there such as Flurry or Google Analytics for iOS.

In the spirit of keeping this post short, I’ll continue with the rest of my list in a later post. To get it delivered straight to your inbox, subscribe for free.

Continue to Part 2

Related article: Top 10 Lessons learned from launching iPhone Apps

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS

8 Great Open Source Projects to use in your next iPhone App

I’ve scoured the internet looking for great open source iOS apps, and what I determined is that what is really more interesting is the open source iOS components and frameworks. So here’s my list of the most useful open source iOS components.

8. PSCollectionView
PSCollectionView is a custom collection view that allows for the easy creation of Pinterest-style image collections in your iOS apps. Source on Github


7. GMGridView
This little grid view library allows for the simple creation of highly interaction view sets. You can see a nice video of an example result hereSource on Github


6. PRTween

PRTween is an extension of the core animation framework. It is an effort to take the power of core animation, and make it easier to use. The commands available may remind some of the stupid-simple jQuery animation commands like fade, hide, or show. Source on Github



5. iHasApp
I recently was asked by a client if we could detect their other apps installed on the device, and if the user didn’t own them if we could have the app present cross-promotional ads. I wasn’t sure what the answer to their question was, it seemed like something that might fall under the dreaded “private api” category. But here this project is an App Store friendly library to detect other apps installed on the user’s phone. Source on Github


4. NUI
NUI is a very interesting project that aims to make styling of iOS apps as easy as styling in CSS. Take a look at the syntax on the project’s github page and you’ll see what makes this such an interesting project. Source on Github


3. grabKit
If you are writing an iPhone app that involves the user’s photos, one thing that’s always a bit tricky is adding support for all the various social networks that the user might prefer to host their photos on. grabKit makes this easier with this drop-in library that let’s the user import photos from Facebook, Flickr, Instagram, Picasa, or the iOS device itself. Source on Github


2. MultistrokeGestureRecognizer
This library is great for anyone creating a very touch-centric game, or any app that uses lots of complex gestures. The library is based on the N Multistroke Recognizer which is a great algorithm for detecting very complex touch gestures. If you remember the gestures in the game Black & White, it’s kind of like that. Source on Github


1. Filepicker
Similar to grabKit, Filepicker allows for the importing of files from various social networks, but also includes many more services such as Dropbox, Gmail, and even Github. The library is also not limited to only photos but can be used for a range of content types. Source on Github


Honorable mention: cupertino
Cupertino is not an iOS library, but rather a ruby gem that allows for administration of your Apple Developer Account. This has been a missing piece of the formula for automating iOS development work for years, so I’m glad to see some hackers have decided to take up the challenge of making a CLI for the Apple Developer Account system.

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS

iPhone review process

I think twitter has spoiled me in to thinking I can write a one-sentence statement and actually be contributing something to the internet. Maybe it’s time to start writing in my blog more, it’s been 4 months. All I have to say right now though is that I have been incredibly busy for the past 4 months with my clients, and on the side I wrote an iPhone game. The game is sort of a joint project with a friend of mine, and we really probably only spent 3 or 4 working days time to build it. I submitted it to the app store about a week ago, but we are still in the App Review queue. I will report back here any further details on how it goes… It seems like I should be more excited about my first actual product, but somehow I guess I’m not feeling it. Probably because we made it so quickly I don’t even have any attachment to the project. I guess this is more of an experiment with the App Store, and a test of my 2D engine. Well, wish me luck!

Did this tutorial help you?

Support my Patreon

Your support on Patreon allows me to make better tutorials more often.

Subscribe via RSS