cover.eps

Pushing the Limits with iOS 5 Programming: Advanced Application Development for Apple iPhone®, iPad®, and iPod® Touch

Table of Contents

Pushing the Limits with iOS 5 Programming

Advanced Application Development for Apple iPhone®, iPad®, and iPod® Touch

Rob Napier and Mugunth Kumar

229_x_152_v2_title_c_logo.eps

Dedication

To Neverwood. Thanks for your patience.
Rob

To my mother who shaped the first twenty years of my life
Mugunth

Publisher’s Acknowledgements

Some of the people who helped bring this book to market include the following:

Editorial and Production

VP Consumer and Technology Publishing Director: Michelle Leete

Associate Director–Book Content Management: Martin Tribe

Associate Publisher: Chris Webb

Acquisitions Editor: Chris Katsaropolous

Assistant Editor: Ellie Scott

Development Editor: Tom Dinse

Copy Editor: Maryann Steinhart

Technical Editor: Mithilesh Kumar

Editorial Manager: Jodi Jensen

Senior Project Editor: Sara Shlaer

Editorial Assistant: Leslie Saxman

Marketing

Associate Marketing Director: Louise Breinholt

Marketing Executive: Kate Parrett

Composition Services

Compositor: Wiley Indianapolis Composition Services

Proofreaders: Laura Albert, Lindsay Amones, Melissa D. Buddendeck, Melissa Cossell

Indexer: Potomac Indexing, LLC

About the Authors

Rob Napier is a builder of tree houses, hiker, and proud father. He began developing for the Mac in 2005, and picked up iPhone development when the first SDK was released, working on products such as The Daily, PandoraBoy, and Cisco Mobile. He is a major contributor to Stack Overflow and maintains the Cocoaphony blog ().

Mugunth Kumar is an independent iOS developer based in Singapore. He graduated in 2009 and holds a Masters degree from Nanyang Technological University, Singapore, majoring in Information Systems. He writes about mobile development, software usability, and iOS-related tutorials on his blog ().Prior to iOS development he worked for Fortune 500 companies GE and Honeywell as a software consultant on Windows and .NET platforms. His core areas of interest include programming methodologies (Object Oriented and Functional), mobile development and usability engineering. If he were not coding, he would probably be found at some exotic place capturing scenic photos of Mother Nature.

About the Technical Editor

Mithilesh Kumar is a software engineer with a passion for user interface design, Internet protocols, and virtual worlds. He likes to prototype and build applications for iOS and Mac OS X platforms. He has extensive experience in developing UI and core components for telephony clients capable of voice, video, instant messaging, presence, and voicemail.

Mithilesh graduated with a Masters degree in Computer Science from Virginia Tech with emphasis on Human-Computer Interaction. While at graduate school, he co-authored several research papers in the area of user interfaces, computer graphics and network protocols.

Authors’ Acknowledgements

Rob thanks his family for giving up many evenings that he spent in the basement writing, hacking, and otherwise failing to come upstairs. Mugunth thanks his parents and friends for their support while writing this book. Thanks to Wiley for making this book possible. It went extremely well, particularly due to Sara Shlaer’s continual guiding hand. Thanks to Mithilesh Kumar who made sure what we said was true, and Tom Dinse who made sure that it was intelligible. Thanks to Chris Katsaropoulos for first reaching out and getting this project rolling. Thanks to the Apple engineers who answer questions on development forums on all those still-under-NDA issues, and the whole iOS developer community who share so much. And special thanks to Steve Jobs for building toys we could build a career around.

Introduction

Apple has a history of alternating its releases between user-focus and developer-focus. The good news about iOS 5 is that it’s all about the developers. The addition of Automatic Reference Counting (ARC) alone is worth the upgrade for developers. In one move, Apple has eliminated the number one cause of crashes in iOS applications, while making the code easier to write and faster to run. Moving to ARC is the single best thing you can do for your application. It’s the most important Objective-C feature since the autorelease pool.

But iOS 5 adds many more features for the developer. From iCloud to automatic data protection, the operating system now takes care of more of the hard problems, letting developers focus on making the best apps.

Most visible to developers is the new Xcode. Some of it is better, some of it is just different, and some of it will make you crazy. It’s the new game in town, though, and everyone needs to get used to it. This book will help you figure it out.

If you’re ready to take on the newest Apple release and push your application to the limits, this is the book to get you there.

Who This Book Is For

This is not an introductory book. There are many books out there that will teach you Objective-C and take you step by step through Interface Builder. This is not that book. This book assumes that you have a little experience with iOS. Maybe you’re self-taught, or maybe you’ve taken a class. You’ve hopefully written at least most of an application, even if you haven’t submitted it yet. If you’re ready to move beyond the basics, to learn the best practices and the secrets that the authors have learned from practical experience writing real applications, then this is the book for you.

This book also is not just a list of recipes. There’s plenty of sample code here, but the focus is on learning how to design, code, and maintain great iOS apps. A lot of this book is about why rather than just how. You’ll learn about as much about design patterns and writing reusable code as about syntax and new frameworks.

All the examples use Xcode 4. If you’re not comfortable with Xcode 4 yet, don’t worry. Chapter 2 is devoted to getting you up to speed.

What This Book Covers

The iOS platforms always move forward, and so does this book. Most of the examples here require iOS 5. All examples use Automatic Reference Counting. Except in a very few places, this book will not cover backward compatibility. If you’ve been shipping code long enough to need backward compatibility, you probably know how to deal with it. This book is about writing the best-possible apps using the best features available.

This book focuses on the iPhone 4 and iPad 2. Most topics here are applicable to the original iPad, iPod touch, iPhone 3GS, and Apple TV. At the time of writing the iPhone 5 and iPad 3 have not been released, but everything here should apply to them as well. Chapter 12 is devoted to dealing with the differences between the platforms.

How This Book Is Structured

iOS has an extremely rich set of tools, from high-level frameworks like UIKit to very low-level tools like Core Text. Often, there are several ways to achieve a goal. As a developer, how do you pick the right tool for the job?

This book separates the everyday from the special purpose, helping you pick the right solution to each problem. You’ll learn why each framework exists, how the frameworks relate to each other, and when to choose one over another. Then you’ll learn how to make the most of each framework for solving its type of problem.

There are four parts to this book, moving from the most common tools to the most powerful:

Part I: What’s New?

If you’re familiar with iOS 4, then this section quickly introduces you to the new features of iOS 5.

Chapter 1: The Brand New Stuff — iOS adds a lot of new features, and here you get a quick overview of what’s available.

Chapter 2: Getting Comfortable with Xcode 4 — Apple recently redesigned the Xcode interface, and it can take some getting used to. This chapter shows you how to get the most out of it.

Part II: Getting the Most Out of Everyday Tools

As an iOS developer, you’ve encountered a wide variety of common tools, from notifications to table views to animation layers. But are you using these tools to their full potential? In this part, you learn the best practices in Cocoa development from seasoned developers.

Chapter 3: Everyday Objective-C—If you’re ready to move to the next level in Objective-C, this chapter introduces you to the tools experienced developers use every day to improve application design, maintainability, and reusability.

Chapter 4: Hold On Loosely: Cocoa Design Patterns—Cocoa relies on a number of common and consistent design patterns. You learn what they are so you can solve problems the same way Apple does.

Chapter 5: Getting Table Views Right—Table views are perhaps the most complex and commonly used UI element in iOS. They are simple and elegant in design, but confusing to developers who don’t understand how they work. You learn how to use them correctly and to solve some special problems like infinite scrolling.

Chapter 6: Better Drawing—Custom drawing is intimidating to many new developers, but it’s a key part of building beautiful and fast user interfaces. You’ll discover the available drawing options from UIKit to Core Graphics, and how to optimize them to look their best while keeping them fast.

Chapter 7: Layers Like an Onion: Core Animation—iOS devices have incredible facilities for animation. With a powerful GPU and the highly optimized Core Animation, you can build engaging, exciting, and intuitive interfaces. In this chapter, you go beyond the basics and learn the secrets of animation.

Chapter 8: Tackling Those Pesky Errors—You try to write perfect code, but sometimes things go wrong. How your application reacts to the unexpected is what separates decent apps from extraordinary apps. You’ll learn the common patterns for error handling, how to log, and how to make your code more resilient against the unexpected.

Part III: The Right Tool for the Job

There are tools that are part of nearly every application, and there are tools that you only need from time to time. In this section, you learn about those tools and techniques that are a little more specialized.

Chapter 9: Controlling Multitasking—Multitasking is an important part of many applications, and you learn how to do multiple things at once while your application is running and when your application is in the background.

Chapter 10: REST for the Weary—REST-based services are a mainstay of modern applications, and you learn how to best implement them in iOS.

Chapter 11: Batten the Hatches with Security Services—User security and privacy are paramount today, and you learn how to protect your application and user data from attackers with the keychain, certificates, and encryption.

Chapter 12: Running on Multiple iPlatforms and iDevices—The iOS landscape gets more complex every year with iPod touch, iPhone, iPad, Apple TV, and a steady stream of new editions. It’s not enough just to write once, run everywhere. You need your applications to be their best everywhere. You’ll learn how to adapt your apps to the hardware and get the most out of every platform.

Chapter 13: Internationalization and Localization—While you may want to focus on a single market today, there are small things you can do to ease the transition to a global market tomorrow. Save money and headaches later, without interrupting today’s development.

Chapter 14: Selling Past the Sale with In App Purchases—In App Purchases are still an untapped market for many developers. Users like the add-on content, and developers love the extra revenue. You learn the best ways to make this important feature a reality in your application.

Part IV: Pushing the Limits

This section is what this book is all about. You’ve learned the basics. You’ve learned the everyday. Now push the limits with the most advanced tools available. You learn the ins and outs of deep iOS.

Chapter 15: Cocoa’s Biggest Trick: Key-Value Observing—Many of Apple’s most powerful frameworks rely on KVO for their performance and flexibility. You learn how to leverage the flexibility and speed of KVO, as well as the trick that makes it so transparent.

Chapter 16: Think Different: Blocks and Functional Programming—Many developers are still absorbing the addition of blocks to Objective-C. They’re valuable for interacting with Apple frameworks, but they also open new ways of thinking about your program. Embrace a new style, and maximize its benefits in your next project.

Chapter 17: Going Offline—Network programming is hard, but even harder is providing a seamless offline experience. Learn how to best cache your data and integrate it into your network engine.

Chapter 18: Fancy Text Layout—From UIKit to Core Text, iOS is full of ways to display text. There’s no perfect solution for displaying rich text in iOS, so it’s important to learn the trade-offs so you can choose the right solution and use it correctly.

Chapter 19: Building a (Core) Foundation—When you want the most powerful frameworks available on iOS, you’re going to want the Core frameworks like Core Graphics, Core Animation, and Core Text. All of these rely on Core Foundation. In this chapter you learn how to work Core Foundation data types so you can leverage everything iOS has to offer.

Chapter 20: Deep Objective-C—When you’re ready to pull back the curtain on how Objective-C really works, this is the chapter for you. You learn how to use the Objective-C runtime directly to dynamically modify classes and methods. You also learn how Objective-C method calls are dispatched to C function calls, and how you can take control of the system to extend your programs in incredible ways.

You can skip around in this book to focus on the topics you need most. Each chapter stands alone, except for those that require Core Foundation data objects (particularly Core Graphics, Core Animation, and Core Text). Those chapters direct you to Chapter 19, “Building a (Core) Foundation,” when you need that information.

What You Need to Use This Book

All examples in this book were developed with Xcode 4.2 on Mac OS X 10.7 and iOS 5. You need an Apple developer account to access most of the tools and documentation, and you need a developer license to run applications on your iOS device. Visit to sign up.

Most of the examples in this book will run in the iOS Simulator that comes with Xcode 4.2. You can use the iOS Simulator without an Apple developer license.

There are few differences between Xcode 4.2 on Mac OS X 10.6 and 10.7, so all examples should work under 10.6.

Finding Apple Documentation

Apple provides extensive documentation at its website and within Xcode. The URLs change frequently and are often very long. This book refers to Apple documents by title rather than by URL. To find documents in Xcode, press Cmd-Option-? or click Help Documentation and API Reference. In the Documentation Organizer, click the Search icon, type in the name of the document, and then select the document from the search results. See Figure 1 for an example of how to search for the Coding Guidelines for Cocoa.

9781119961321-unin01.eps

Figure 1 Searching for Coding Guidelines for Cocoa

To find documents at the Apple developer site, visit , click Member Center and log in. Select the iOS Dev Center, and enter the document title in the Search Developer search box.

The online documentation is generally identical to the Xcode documentation. You may receive results for both iOS and Mac. Make sure to choose the iOS version. Many iOS documents are copies of their Mac counterparts, and occasionally include function calls or constants that are not available on iOS. This book guides you about which features are available on iOS.

Source Code

As you work through the examples in this book, you may choose either to type in all the code manually or to use the source code files that accompany the book. All of the source code used in this book is available for download at . For example, you will find the following sample code online in the Chapter 18 folder, in the SimpleLayout project, and the CoreTextLabel.m file:

CoreTextLabel.m (SimpleLayout)

- (id)initWithFrame:(CGRect)frame {

  if ((self = [super initWithFrame:frame])) {

    CGAffineTransform

    transform = CGAffineTransformMakeScale(1, -1);

    CGAffineTransformTranslate(transform,

                               0, -self.bounds.size.height);

    self.transform = transform;

    self.backgroundColor = [UIColor whiteColor];

  }

 return self;

 }

Some source code snippets shown in the book are not comprehensive and are meant to help you understand the chapter. For those instances, you should refer to the files available on the website for the complete source code.

Part I: What’s New?

Chapter 1 The Brand New Stuff

Chapter 2 Getting Comfortable with Xcode 4

Chapter 1: The Brand New Stuff

In 2007, the late Steve Jobs took the stage at Macworld and proclaimed that software running on iPhone was at least five years ahead of the competition. Since its initial release, Apple has been iterating the operating system year after year, and has even added two new devices, the iPad and Apple TV, to the list of products capable of running it. As the operating system was customized to run on more devices than just the iPhone, it was rebranded as iOS. Today, it’s almost 5 years old, and iOS 5 is easily the biggest update to iOS since the original launch, possibly making the software five years ahead of the competition again.

This book is about programming with iOS 5. Targeting intermediate to advanced iOS developers, this book, unlike most others, covers advanced topics of iOS development. Rather than learning about frameworks and the features available on the iOS SDK, you learn about how to make the best use of those features to help push your apps to the next level. This chapter briefly describes the new features covered in detail in the book and tells you the chapters in which they are discussed.

The History of iOS

The second version, iPhone OS 2, was the first to have a public SDK. From then on, with every release of the operating system, Apple introduced several major features and a lot more minor API changes. This section briefly describes the history of the iOS. The remaining sections in the chapter provide an overview of what’s new in iOS 5.

iPhone OS 3 brought Core Data from Mac to iPhone. Other additions include Apple Push Notification Service, External Accessory Kit, In App Purchases through the StoreKit.framework, in app email sheets, the MapKit.framework that allows developers to embed Google Maps into their apps, read-only access to the iPod library, and keychain data sharing. OS 3.1 added video editor support, a minor update. iPhone OS 3.2 added Core Text and gesture recognizers, file sharing, and PDF generation support, another minor (yet so major) update. OS 3.2 also added a whole new product, iPad, support for developing apps that run on iPad, and universal apps that run on iPad (3.2) and iPhone (3.1.3). 3.2 was iPad only and didn’t run on iPhone or iPod touch devices.

iPhone OS 4 (rebranded as iOS 4) introduced much-awaited multitasking support, local notifications, read-only access to calendar (Event Kit framework, EventKit.framework), blocks, Grand Central Dispatch (GCD), in app message composer sheets (SMS), and Retina display support. This version was iPhone only and didn’t support developing apps for iPad. A minor update, iOS 4.2, unified iPhone and iPad operating systems.

What’s New

iOS 5 introduces several important features like iCloud, Automatic Reference Counting (ARC), Storyboards, built-in Twitter framework, and several other minor features. The next few sections introduce you to the key features added to iOS 5 and the chapters in which they are discussed in detail and where I provide guidance about how to push your apps to the next level.

iCloud

iCloud is a new cloud service provided by Apple. iCloud differs from competing similar offerings in that it’s more a cloud-based service than cloud-based storage. Developers have been using third-party services for synchronizing data across multiple devices. Dropbox is the most popular of these services; however, even Dropbox API version 0 (the latest version as of this writing), doesn’t support conflict handling, something that’s critical for data integrity. While Dropbox has conflict resolution, it’s not exposed to developers via their API. iCloud, on the other hand, supports file storage and has conflict resolution built into the iOS 5 SDK.

iCloud also supports storing key-value data on the cloud, which is good enough for apps that need settings and other similar data to be kept in sync.

iCloud is not just a hard disk on the cloud. Think of iCloud as a cloud-based service that just happens to support data storage.

iOS 5 adds several new APIs for adding iCloud support:

UIDocument (very similar to its kin, NSDocument, on Mac)

UIManagedDocument, for managing your Core Data storage

Additions to NSFileManager to move and restore files from iCloud

iCloud is covered in detail in Chapter 17.

LLVM 3.0 Compiler

LLVM (Low Level Virtual Machine) is a new compiler project partly funded by Apple. While technically not a part of iOS 5, developers should be equipped with the knowledge of the new features available in LLVM. Improved auto complete and speedier compilation are just a part of LLVM’s new features. In Chapter 2 you learn about the features of LLVM and how LLVM augments Xcode 4’s features.

Automatic Reference Counting

Another important feature of iOS 5 is Automatic Reference Counting (ARC). It is a compiler-level feature provided by the new LLVM compiler. This means that you can use it without increasing the minimum SDK support to iOS 5. ARC can be used in apps targeting iOS 4 onward, and Xcode 4.2 also provides support for migrating your code to use ARC using the Convert to Objective-C ARC tool. With the new LLVM compiler slowly becoming mainstream, ARC will supercede the current retain/release memory management.

Automatic Reference Counting is not like garbage collection offered on Mac OS X from version 10.5 (Leopard). Garbage collection is automatic memory management. This means that developers don’t have to write a matching release for every retain statement. The compiler automatically inserts them for you.

ARC adds two new lifetime qualifiers—strong and weak—and it also imposes new rules, such as that you can no longer invoke release, retain on any object. This applies to custom dealloc methods as well. When using ARC, your custom dealloc methods should only release resources (files or ports) and not instance variables.

ARC is covered in detail in Chapter 3.

Storyboards—Draw Your Flow

Storyboards is a new way to design your user interface. Prior to iOS 5 you used Interface Builder nib files to define your UI one view controller at a time. With Storyboards, you can define in one file the complete UI flow of your app, including interaction among the different view controllers.

You can use Storyboards to define all view controllers in your app. You don’t have to create multiple Storyboards or worry about performance. The Interface Builder build tool automatically splits your storyboard file into parts and loads it individually at runtime without affecting performance.

On iOS 5, storyboards replace MainWindow.xib nib file (and possibly every other view controller’s nib file). The new project template in Xcode 4.2 helps in creating storyboards. You can also add a storyboard to your old projects and optionally make it the main storyboard by adding an entry to the Info.plist file.

Storyboards, unlike ARC, is an iOS 5-specific feature, and using Storyboards means that you need to raise your minimum supported OS to iOS 5.

You will learn more about storyboards in Chapter 5.

UIKit Customization—Appearance Proxy

Apple (and even Microsoft) has always been against UI customization, or theming. Its reasoning is that theming makes it difficult for users to understand the user interface. The Web, on the other hand, has made a huge revolution on this front and this has had an effect on the latest release of iOS as well. Beginning with iOS 5, some native apps like Reminders get some rich customization. With iOS 5, most properties of UIKit elements can be customized. This includes backgroundColor, tintColor, and a lot more. Customization is supported by a UIView subclass if it implements the UIAppearance protocol. The protocol also allows customization based on the contained view. For example, you can have a different tint when a custom view of yours is within a navigation bar.

Chapter 5 covers UI customization.

Twitter Framework and Accounts Framework

iOS 5 integrates Twitter experience right into the OS. This means sending a tweet from your app is as easy as sending an email using an in app email sheet. The framework also handles authentication for you, which means you no longer need to do the oAuth/xAuth authentication yourself. Twitter framework on iOS 5 integrates with Accounts framework to provide account authentication. As of this writing, Twitter is the only third-party authentication system supported natively on iOS 5. But, by looking at the decoupled design of Twitter framework and Accounts framework, there is a possibility that additional services might be introduced later on. While there are some advantages of using these frameworks, it’s still an iOS 5-specific feature, which means that using it requires you to limit your app to devices running iOS 5 and later. Additionally, when you send out a tweet through iOS, you will not be able to customize the sender (via text). As such, your tweet will be sent as “via iOS.” (See Figure 1-1.)

9781119961321-fg0101.eps

© Twitter 2011

Figure 1-1 Screenshot from Twitter.com showing the “via” text

When you create a new application on Twitter, you can name it so when you tweet using this application’s credentials, its name shows up in the “via” text. The built-in Twitter.framework on iOS 5 doesn’t allow setting this text, so if you are considering using Twitter for increasing your brand’s reach, you may have to evaluate branding versus ease of development.

Adding Twitter experience to your app with the new Twitter.Framework is as easy as sending an in app email. This differs from an app email in one aspect. Instead of providing a delegate callback, the TWTweetComposeViewController of Twitter.Framework provides a completionHandler. Chapter 16 shows you an example of this in action.

Other New Features

In addition to the “big” features discussed in the preceding sections, iOS 5 also adds several other features, including dedicated support for magazine apps, a native image processing library, AirPlay mirroring support, and new controls added to UIKit.framework.

Newsstand Kit

Newspaper or magazine apps can make use of the NewsstandKit.framework to deliver digital content. Although it was technically possible to do something similar with iOS 4, iOS 5 introduces several new APIs to enable content for the latest release to be downloaded in the background. Additionally it also enables publishers to provide a cover art image (front cover) for their magazine instead of an icon. Apps developed using this framework appear within the Newsstand app and display the cover art instead of the app icon.

Core Image for Image Processing

Camera apps can use features in Core Image to apply image processing filters. The classes CIImage and CIFilter add basic image-editing functions like cropping, rotation (affine transform), and color inversion, to advanced features like gamma correction, white point adjustment, false color, sepia toning, temperature and tint correction, and many more that would be present in any entry-level image editor. This feature of iOS 5 will be tremendously useful for camera-enhancement apps that compete with apps like Instagram or Camera+. iPhone camera is already the most popular camera on Flickr. This framework will take it even further.

Core Image for Feature Detection

Core Image has another important element: feature detection. At WWDC 2011, Apple demonstrated a feature of Photo Booth that tracks the location of a face and adorns it with birds circling the head. With Core Image, you can add such features with very little programming effort. The class CIDetector has a convenient featuresInImage: method that returns a list of CIFeature objects detected in the given image.

Core Image is discussed in Chapter 6.

Other Minor Enhancements

iOS 5 adds many other minor enhancements like AirPlay video support, mirroring (which can be disabled by your app if you are showing protected content); better document support; improvements in data protection (Chapter 11); a new control, UIStepper; capability to add a password entry field to the UIAlertView just like the AppStore password prompt; a new UIPageViewController for creating page curl effects like iBooks; and much more. All these major and minor enhancements together make iOS 5 the biggest enhancement since its inception.

Summary

Adoption rates of iOS have always been way ahead of the competition. A couple of years ago, when iPhone OS 3.0 was launched, adoption rates were partly hindered on iPod touch because the upgrade cost $10. However, Apple soon made it free and adoption rates increased. Similarly, when Apple released iOS 4, the adoption rate was initially slow because of performance issues on older phones such as iPhone 3G and the original iPhone (and equivalent iPod touches). Some features—mainly multitasking—were also not available for older devices. Nevertheless, the latest iOS usually gets adopted on more than 90 percent of devices within the first two months of launch.

With iOS 5, adoption rates should be the fastest ever for the following reasons. First, the update is free for all devices, unlike iPhone OS 3. Second, unlike iOS 4, iOS 5 doesn’t make older devices (the iPhone 3GS) run slower. Finally, for end users, cleaner notifications, iTunes wi-fi sync, and iMessage are killer features that should accelerate iOS 5 adoption.

All this means that you should start using every iOS 5 feature as soon as possible to get your app to shine in all its glory. Features like iCloud and UIKit customizations alone should be reason enough to update your apps to iOS 5. That said, the next chapters start you on your iOS 5 journey.

Further Reading

Apple Documentation

The following documents are available in the iOS Developer Library at or through the Xcode Documentation and API Reference.

iCloud

What’s New in iOS 5

Twitter Framework

Accounts Framework

Other Resources

How is a file conflict detected using the API - Dropbox forums