Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Swift 2 Blueprints
Swift 2 Blueprints

Swift 2 Blueprints: Swift Blueprints

eBook
S$36.99 S$52.99
Paperback
S$66.99
Subscription
Free Trial

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Swift 2 Blueprints

Chapter 2. Creating a City Information App with Customized Table Views

If you've ever developed an app for iOS, you've probably already used a table view. However, you might not have developed it with customized table views or used alternatives for it like the collection view or the page view controller.

Let's start with a simple but a very good app to warm up the engines and learn different ways of displaying collected information with Swift.

In this chapter, we will cover the following:

  • Using table view and custom table view cells
  • The usage of UIPageViewController
  • The usage of UICollectionViewController
  • The usage of external APIs
  • Managing JSON messages
  • The usage of NSURLSession to receive JSON or download pictures
  • Custom NSErrors

Project overview

The idea of this app is to give users information about cities such as the current weather, pictures, history, and cities that are around.

How can we do it? Firstly, we have to decide on how the app is going to suggest a city to the user. Of course, the most logical city would be the city where the user is located, which means that we have to use the Core Location framework to retrieve the device's coordinates with the help of GPS.

Once we have retrieved the user's location, we can search for cities next to it. To do this, we are going to use a service from http://www.geonames.org/.

Another piece of information that will be necessary is the weather. Of course, there are a lot of websites that can give us information on the weather forecast, but not all of them offer an API to use it for your app. In this case, we are going to use the Open Weather Map service.

What about pictures? For pictures, we can use the famous Flickr. Easy, isn't it? Now that we have the...

Setting it up

Before we start coding, we are going to register the needed services and create an empty app. First, let's create a user at geonames. Just go to http://www.geonames.org/login with your favorite browser, sign up as a new user, and confirm it when you receive a confirmation e-mail. It may seem that everything has been done, however, you still need to upgrade your account to use the API services. Don't worry, it's free! So, open http://www.geonames.org/manageaccount and upgrade your account.

Tip

Don't use the user demo provided by geonames, even for development. This user exceeds its daily quota very frequently.

With geonames, we can receive information on cities by their coordinates, but we don't have the weather forecast and pictures. For weather forecasts, open http://openweathermap.org/register and register a new user and API.

Lastly, we need a service for the cities' pictures. In this case, we are going to use Flickr. Just create a Yahoo! account...

The first scene

Create a project group (command + option + N) for the view controllers and move the ViewController.swift file (created by Xcode) to this group. As we are going to have more than one view controller, it would also be a good idea to rename it to InitialViewController.swift:

The first scene

Now, open this file and rename its class from ViewController to InitialViewController:

class InitialViewController: UIViewController {

Once the class is renamed, we need to update the corresponding view controller in the storyboard by:

  • Clicking on the storyboard.
  • Selecting the view controller (the only one we have till now).
  • Going to the Identity inspector by using the command + option + 3 combination. Here, you can update the class name to the new one.
  • Pressing enter and confirming that the module name is automatically updated from None to the product name.

The following picture demonstrates where you should do this change and how it should be after the change:

The first scene

Great! Now, we can draw the scene. Firstly, let&apos...

Displaying the cities' information

The next step is to create a class to store the information received from the Internet. In this case, we can do it in a straightforward manner by copying the JSON object properties in our class properties. Create a new group called Models and, inside it, a file called CityInfo.swift. There you can code CityInfo as follows:

class CityInfo {
    var fcodeName:String?
    var wikipedia:String?
    var geonameId: Int!
    var population:Int?
    var countrycode:String?
    var fclName:String?
    var lat : Double!
    var lng: Double!
    var fcode: String?
    var toponymName:String?
    var name:String!
    var fcl:String?
    
    init?(json:JSON){){){
        // if any required field is missing we must not create the object.
        if let name = json["name"].string,,, geonameId = json["geonameId"].int, lat = json["lat"].double,
            lng = json["lng"].double {
            self.name = name
            self...

Coding the initial view controller

The InitialViewController class will display the possible cities where the user is located. Let's continue with the InitialViewController class and complete its code. To complete this code, we need to think about where we are going to store the received information. We will need two arrays of CityInfo: one is to store every object received from the server and the other is to store the objects that are shown after the user's filter. These arrays must be stored as properties:

    private var cities = [CityInfo]()
    private var citiesDisplayed = [CityInfo]()

At this point, we can complete the didUpdateLocations method, which belongs to the CLLocationManagerDelegate protocol. Now, we can request information of the cities that are around us. Type the following code to implement the didUpdateLocations method, replacing the yourgeonamesuser word with the username you registered on geonames:

    func locationManager(manager: CLLocationManager!, didUpdateLocations...

Project overview


The idea of this app is to give users information about cities such as the current weather, pictures, history, and cities that are around.

How can we do it? Firstly, we have to decide on how the app is going to suggest a city to the user. Of course, the most logical city would be the city where the user is located, which means that we have to use the Core Location framework to retrieve the device's coordinates with the help of GPS.

Once we have retrieved the user's location, we can search for cities next to it. To do this, we are going to use a service from http://www.geonames.org/.

Another piece of information that will be necessary is the weather. Of course, there are a lot of websites that can give us information on the weather forecast, but not all of them offer an API to use it for your app. In this case, we are going to use the Open Weather Map service.

What about pictures? For pictures, we can use the famous Flickr. Easy, isn't it? Now that we have the necessary information...

Setting it up


Before we start coding, we are going to register the needed services and create an empty app. First, let's create a user at geonames. Just go to http://www.geonames.org/login with your favorite browser, sign up as a new user, and confirm it when you receive a confirmation e-mail. It may seem that everything has been done, however, you still need to upgrade your account to use the API services. Don't worry, it's free! So, open http://www.geonames.org/manageaccount and upgrade your account.

Tip

Don't use the user demo provided by geonames, even for development. This user exceeds its daily quota very frequently.

With geonames, we can receive information on cities by their coordinates, but we don't have the weather forecast and pictures. For weather forecasts, open http://openweathermap.org/register and register a new user and API.

Lastly, we need a service for the cities' pictures. In this case, we are going to use Flickr. Just create a Yahoo! account and create an API key at https...

The first scene


Create a project group (command + option + N) for the view controllers and move the ViewController.swift file (created by Xcode) to this group. As we are going to have more than one view controller, it would also be a good idea to rename it to InitialViewController.swift:

Now, open this file and rename its class from ViewController to InitialViewController:

class InitialViewController: UIViewController {

Once the class is renamed, we need to update the corresponding view controller in the storyboard by:

  • Clicking on the storyboard.

  • Selecting the view controller (the only one we have till now).

  • Going to the Identity inspector by using the command + option + 3 combination. Here, you can update the class name to the new one.

  • Pressing enter and confirming that the module name is automatically updated from None to the product name.

The following picture demonstrates where you should do this change and how it should be after the change:

Great! Now, we can draw the scene. Firstly, let's change...

Displaying the cities' information


The next step is to create a class to store the information received from the Internet. In this case, we can do it in a straightforward manner by copying the JSON object properties in our class properties. Create a new group called Models and, inside it, a file called CityInfo.swift. There you can code CityInfo as follows:

class CityInfo {
    var fcodeName:String?
    var wikipedia:String?
    var geonameId: Int!
    var population:Int?
    var countrycode:String?
    var fclName:String?
    var lat : Double!
    var lng: Double!
    var fcode: String?
    var toponymName:String?
    var name:String!
    var fcl:String?
    
    init?(json:JSON){){){
        // if any required field is missing we must not create the object.
        if let name = json["name"].string,,, geonameId = json["geonameId"].int, lat = json["lat"].double,
            lng = json["lng"].double {
            self.name = name
            self.geonameId = geonameId
            self.lat...

Coding the initial view controller


The InitialViewController class will display the possible cities where the user is located. Let's continue with the InitialViewController class and complete its code. To complete this code, we need to think about where we are going to store the received information. We will need two arrays of CityInfo: one is to store every object received from the server and the other is to store the objects that are shown after the user's filter. These arrays must be stored as properties:

    private var cities = [CityInfo]()
    private var citiesDisplayed = [CityInfo]()

At this point, we can complete the didUpdateLocations method, which belongs to the CLLocationManagerDelegate protocol. Now, we can request information of the cities that are around us. Type the following code to implement the didUpdateLocations method, replacing the yourgeonamesuser word with the username you registered on geonames:

    func locationManager(manager: CLLocationManager!, didUpdateLocations...
Left arrow icon Right arrow icon

Key benefits

  • Develop a variety of iOS-compatible applications that range from health and fitness to utilities using this project-based handbook
  • Discover ways to make the best use of the latest features in Swift to build on a wide array of applications
  • Follow step-by-step instructions to create Swift apps oriented for the real world

Description

In this book, you will work through seven different projects to get you hands-on with developing amazing applications for iOS devices. We start off with a project that teaches you how to build a utility app using Swift. Moving on, we cover the concepts behind developing an entertainment or social networking related application, for example, a small application that helps you to share images, audio, and video files from one device to another. You’ll also be guided through create a city information app with customized table views, a reminder app for the Apple Watch, and a game app using SpriteKit. By the end of this book, you will have the required skillset to develop various types of iOS applications with Swift that can run on different iOS devices. You will also be well versed with complex techniques that can be used to enhance the performance of your applications.

Who is this book for?

If you are a competent iOS developer who wants to develop stunning applications with Swift, then this book is for you. Familiarity with Swift programming is assumed.

What you will learn

  • Get to grips with the basics of Xcode and Swift for application development
  • Create a Photo Sharing application to capture an image, edit it using different features and share it via social media.
  • Develop applications using the WatchKit and exchange data between iPhone and the Watch
  • Use advanced features such as SpriteKit to build a game
  • Install third-party Swift frameworks to improvise on your application development
  • Discover how to simulate home automation with HomeKit
  • Build an application to monitor the user s weight, heart rate and the number of steps for Health Historic Analysis
  • Manipulate media using AVFoundation framework to merge audio and video.

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Oct 27, 2015
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781783980765
Category :
Languages :
Tools :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Oct 27, 2015
Length: 276 pages
Edition : 1st
Language : English
ISBN-13 : 9781783980765
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just S$6 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total S$ 153.97
Swift 2 Blueprints
S$66.99
Swift High Performance
S$49.99
Swift 2 Design Patterns
S$36.99
Total S$ 153.97 Stars icon

Table of Contents

9 Chapters
1. Exploring Xcode Chevron down icon Chevron up icon
2. Creating a City Information App with Customized Table Views Chevron down icon Chevron up icon
3. Creating a Photo Sharing App Chevron down icon Chevron up icon
4. Simulating Home Automation with HomeKit Chevron down icon Chevron up icon
5. Health Analyzing App Using HealthKit Chevron down icon Chevron up icon
6. Creating a Game App Using SpriteKit Chevron down icon Chevron up icon
7. Creating an Apple Watch App Chevron down icon Chevron up icon
8. AVFoundation Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Half star icon 4.3
(4 Ratings)
5 star 25%
4 star 75%
3 star 0%
2 star 0%
1 star 0%
G. Campbell Jan 23, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon 5
I really like this book. The introduction which covers Xcode (keyboard shortcuts, version control, testing a UIView in playground, etc.) were helpful, and you can tell this was written by working developers. The sample apps are well presented and the practical approach is carried forward throughout. I think anyone developing apps with Xcode would benefit from this book.
Amazon Verified review Amazon
Robert D. Matthews Dec 10, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I purchased this book from Packt publishing, as I have done a lot with other titles lately.The book is pretty good. I'd probably give it 4.5 stars if that were an option. Very few books will ever get 5 stars.The book starts off with a pretty quick overview on xcode, etc. and then jumps right into talking you through making 7 different apps.The strategy of walking you through is pretty good, it get's your hands dirty and your head around the kinds of things you have to do to make an app. It's not designed to be a technical resource and the book doesn't cover everything, but it does a great job with focusing on several aspects of making an app using swift and some of the right things to do and the wrong things to avoid. They don't spend any time with CoreData but they do throw in a watch app.Overall it's a great book...probably not the first book on iOS programming someone should read but it's a great hands-on walkthrough for someone new to swift.It's a very good technical book for what it's intended for.
Amazon Verified review Amazon
pauland Dec 08, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I'm not new to Swift development but bought this book primarily to get a 'quick start' to building some types of projects and to get an insight into the techniques others are using when building swift applications. This book does not disappoint in that respect.Essentially the book is divided into chapters, with each chapter (except the first) being a run-through of the building of an application. You can see the list of applications from the book preview, but the applications include APIs introduced in IOS9 and the Apple watch.Each application build is well described with all stages of the design and build process explained, though I would say that this is not going to be an easy read for someone who has no experience of IOS/Swift development. It definitely helps to have an idea of the basic concepts first.The book is an excellent resource for building projects quickly. Many of the steps of building typical apps are explained well here, so it forms an excellent resource when a client wants an app that is similar to those presented in the book. It does what it says on the cover - provide a set of swift 2 blueprints/templates that you can build-out as-is or use and adapt in other projects.I am really pleased by the technical content of the book and it is going to speed up my development.In terms of production quality - it is very typically a Packt book. No colour at all in the print version, so greyscale. I really hate greyscale! I wish they would have colour in their books - it would make the book easier to read.I also have an electronic version of the book and that has colour, though disappointingly almost all of the code listings do not have the colour syntax highlights that you would see when working with XCode.I am really pleased with the book and happy to recommend it. It would be five stars if Packt had produced it in colour with colour syntax highlights.
Amazon Verified review Amazon
CandaceVan Nov 22, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I picked up this book because I've been working my way through Swift by Example (also published by Packt), and this looked like a similar kind of book that would teach me how to use some of the frameworks (both Apple and 3rd-party) available to use in iOS development.This is not a beginning book. It assumes that you are familiar with both Xcode and Swift, and after a brief review, it plunges into seven very different projects that range from manipulating photos to creating a 2D game to creating an app for an Apple Watch. Aside from a bit of non-traditional English (clearly comprehensible although obviously written by a non-native author), I have found this book to be, so far, to be a very worthwhile purchase. I'll update my review if my opinion changes by the end of the book!Here's a roundup of what is specifically in the book:Swift 2 Blueprints by Cecil Costa (known as Eduardo Campos in Latin countries), published Oct. 2015 by Packt Publishing, 276 pages. Eight chapters.Chapter 1, "Exploring Xcode," reviews Xcode and Swift features, including: keyboard shortcuts, versioning (Git), testing with playground, debugging (use of _is_ operator, lldb, Fabric), new Swift features (lifting of _let_ limitations, _as_ operator, and introduction of _Set_ to replace _NSSet_).Chapter 2, "Creating a City Information App with Customized Table Views," uses the SwiftyJSON framework to work with JSON messages.Chapter 3, "Creating a Photo Sharing App," teaches how to use the camera, edit a photo, and share it using a social framework.Chapter 4, "Simulating Home Automation with HomeKit," shows how to simulate a house with various devices and create an app to retrieve device info as well as change their settings.Chapter 5, "Health Analyzing App Using HealthKit," teaches the use of HealthKit, as well as a 3rd-party framework, iOS Chart.Chapter 6, "Creating a Game App Using SpriteKit," a framework made for the development of 2-dimensional games.Chapter 7, "Creating an Apple Watch App," develops an app that controls a refrigerator. The amount of food available can be displayed on the watch.Chapter 8, "AVFoundation," uses this low-level framework to change the audio of an existing video from the photo gallery. It will also use the photos framework.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.