Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Swift 2 Blueprints
Swift 2 Blueprints

Swift 2 Blueprints: Swift Blueprints

eBook
£20.98 £29.99
Paperback
£36.99
Subscription
Free Trial
Renews at £16.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

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 : 9781785283741
Category :
Languages :
Tools :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

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

Packt Subscriptions

See our plans and pricing
Modal Close icon
£16.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
£169.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 £5 each
Feature tick icon Exclusive print discounts
£234.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 £5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total £ 85.97
Swift 2 Design Patterns
£20.99
Swift High Performance
£27.99
Swift 2 Blueprints
£36.99
Total £ 85.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

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.