How to Make an App:iOS EDITION
Table of Contents 1   The iOS Revolution 4   Step 1: Define Your App 7   Step 2: Design Your App13   Step 3: The iOS Archit...
1The iOS revolution
2The iOS revolution                                  It’s a story that never gets old. The                                ...
3running at $333 million — a rate of about $4 billion per year —remarkable for a store that only opened in July 2008.Anoth...
2Define your app
5Define your appMost unsuccessful apps fail for any of four reasons:   1. the app was a solution in search of a problem (i....
6must-have core capabilities include:   • Performance (e.g., fast screen refresh)   • Offline capability (i.e., ability to w...
3Design your app
8Design your appUser experience decisions determine the app’s look and feel. Theyanswer questions such as: What does the a...
9Once you’ve got the overall concept for your app, the next step is toexpress that design in terms of the iOS app architec...
10assurance of having applications pre-approved for quality andcontent prior to going on sale.Xcode. Apple’s all-in-one ID...
11Market Growth. Today, iOS represents less than 15% of the totalsmartphone market, Although the total market (“the whole ...
12                          Getting your                          app approvedLet’s say you’ve already made your iOS app, ...
4The iOS app architecture
14The iOS app architectureAs noted earlier, a key reason why there are so many apps for iOS isbecause developing highly fu...
15   (produced in a model). This is where developers spend most of   their time — constructing the View Controller — by de...
16Outlets. A variable by which a view object can be referenced in acontroller. (For example, if you place a text field to c...
5What’s Xcode?
18What’s Xcode?You can start developing functional, good-looking apps almost fromthe moment you download Xcode, Apple’s in...
19Although you can develop, build and simulate your app on yourcomputer in Xcode, you can’t run your app on a target devic...
20header file in the left pane and its corresponding .m in the right pane.Or you might click on a button object (displayed ...
21Connections inspector to view the outlets and actions of an interfaceobject, to make new connections and to delete exist...
6“Hello World!” sample app
23“Hello World!” sample appThis app displays a button (“Press Me”) and a label (“Label”) so thatwhen the user presses the ...
24                                                                           1Follow these steps to make your app:    1. S...
25fig. 6 Connect the button’s Touch Up Inside event to an action in the ViewController    8. Next step is to create an outl...
26   9. Finally, it’s time to add some logic to the view controller so it      knows what to do when the button is pressed...
7Sample app with a backend
28Sample app with a backendThis second app (named “Kinvey Test Drive”) lets the user type texton an iPhone and save the te...
29         at the very top of the Navigator pane — which displays the Project         editor — and then select the “Build ...
30   fig. 9               fig. 10        fig. 11          fig. 12Test Drive App viewsClicking the “+” toolbar button opens an ...
31fig. 13 Backend collection after saving from the appfig. 14 Backend collection after adding a new row directly.Storyboard ...
32To create this app yourself, you would follow these steps:   • Launch Xcode and select the “Single View Application” tem...
33Add View Controller LogicSince the app performs two basic operations (save data to Kinvey andload data from Kinvey) thes...
34display of the table, and respond to user gestures. For example,swiping a table cell will show the delete button because...
35files for code to copy and paste.For both the save and load operations, however, moving the data inand out of a backend c...
36                                                                                       1       Appendix 1 — Test Drive S...
37{    if (alertView.tag == CREATE_NEW_ENTITY_ALERT_VIEW) {           if (buttonIndex == alertView.firstOtherButtonIndex) ...
38                     [alert show];                     self.objects = [@[testObject] arrayByAddingObjectsFromArray:_-obj...
39    KCSAppdataStore *store = [KCSAppdataStore storeWithCollection:testObjectsoptions:nil];    KCSQuery* query = [KCSQuer...
40{    [super viewDidLoad];    _objects = @[];    [self.refreshControl addTarget:self                             action:@...
41- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath{    return YES;}- (UITableViewC...
42        [store removeObject:objToDelete withCompletionBlock:^(NSArray *objectsOr-Nil, NSError *errorOrNil) {            ...
HOW TO MAKE AN APP: iOS EDITIONWritten by                                    Designed byRandall Cronk                     ...
Upcoming SlideShare
Loading in …5
×

How to Make an App: iOS Edition

1,739 views

Published on

Kinvey’s eBook titled, “How to Make an App: Android Edition” is a step by step guide written by developers, for developers.

Published in: Technology
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,739
On SlideShare
0
From Embeds
0
Number of Embeds
17
Actions
Shares
0
Downloads
29
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

How to Make an App: iOS Edition

  1. 1. How to Make an App:iOS EDITION
  2. 2. Table of Contents 1 The iOS Revolution 4 Step 1: Define Your App 7 Step 2: Design Your App13 Step 3: The iOS Architecture17 Step 4: What is Xcode?22 Step 5: “Hello World” Sample App27 Step 6: Sample App with a Backend
  3. 3. 1The iOS revolution
  4. 4. 2The iOS revolution It’s a story that never gets old. The weekend that iPad Minis and the fourth generation iPads went on sale (November 2-5, 2012) Apple sold over 3 million of the devices — a record for first-weekend iPad sales. Two months earlier the company had set another record: first weekend sales of over 5 million for the iPhone 5. Since the introduc- tion of the first iPhone back in 2007,iOS-based devices (iPhone, iPad, iPad Mini and iPod Touch) continueto rewrite the definition of what constitutes a successful product. Bythe end of 2012, over 400 million iOS devices had been sold.What makes iOS devices so successful? Innovation and productfeatures are clearly a big part. Before the iPhone most people hadnot interacted with a multi-touch interface. They had never zoomedwith a pinch or switched between portrait and landscape by merelyrotating a device in their hand. Carrying a phone that knew wherethey were, could suggest places to eat, and could offer directions onhow to get there was also a novel experience.But features like multi-touch, accelerometers and GPS are only partof the appeal. Even with all its innovations, iOS still might not havetaken off the way it has if the only people figuring out ways to usethose innovations worked at Apple. Most of the capabilities availablein an iPhone or iPad in fact don’t come from Apple at all. They comefrom legions of third-party developers who work in a vast ecosystemthat is also an Apple innovation. That ecosystem includes the iPhone,iPad, iPad Mini, iPods, App Store, iTunes, ad networks — and that’sjust on the consumer side. On the developer side, you have Xcode,App Loader, testing tools, iTunes Connect — the list goes on.As of September 2012, the App Store hosted over 700,000 apps thathave collectively been downloaded over 30 billion times. Applereported for October 2012 that App Store monthly revenues were
  5. 5. 3running at $333 million — a rate of about $4 billion per year —remarkable for a store that only opened in July 2008.Another innovation that has spurred iOS app development is “TheCloud.” Cloud services make it easier for independent developers tocreate, support and make money from their apps. The Cloud solvesdata storage and cross-device and user-to-user sharing problems. Ifan app stores data in the Cloud, that part of the application is calledthe “backend,” while the part of the app that runs on the phone andinteracts with the user is called the “front end.”A cloud may be “private” — i.e., theservices belong to an organizationfor the benefit of its employees andbusiness partners. Or a cloud maybe “public” — i.e., a company (suchas Amazon or Kinvey) owns theservices, which developers can thenintegrate into their own apps. If youare a developer and want to buildyour own backend, you certainly cando that. Whether you want to or notdepends on whether your backend provides functionality common tomany different apps. If it does (as in a shopping cart or user authenti-cation) then perhaps that time and money would be better spent onfeatures that offer unique value to your customer. You may be betteroff hooking into a commercial backend provider via an API. Then youcan focus on what counts most — a unique user experience andapplication-specific functionality. That brings us to the first step inmaking an app.
  6. 6. 2Define your app
  7. 7. 5Define your appMost unsuccessful apps fail for any of four reasons: 1. the app was a solution in search of a problem (i.e., no real need existed) 2. the implementation was poor 3. the app tried to do too much; or 4. the Apple App Store rejected the app (either because the implementation was poor or it violated Apple’s content policies)Keeping the app as simple as possible is the best way to avoid thesepitfalls. Most successful apps (indeed, most successful consumer techproducts) are based on what is called an MVP, or minimum viableproduct. It’s the product with the smallest feature set that can deliverthe core function without any distracting “bells and whistles.” Youknow you have an MVP if the product would no longer function if youremoved any single feature.But what should that core featurebe? One of the best examples of anMVP is Mail. Version 1 (on the Mac)offered a clear, limited and intuitivefeature set whose usefulness wasimmediately obvious to anyone.Today’s iPhone version integratesseamlessly with your phone,contacts and calendaring. It auto-matically corrects spelling as youtype, lets you email photos directlyfrom your photos app, and does much more. But all that came laterand was built on top of a basic core function. And that’s how yourfirst app should be built. The key is to come up with something with aclear value that changes people’s lives.So, in drawing up your MVP feature list, ask yourself what featuresare key to the experience. Some basic market research is probably inorder, starting with a visit to the App Store to see what already exists(possibly to be improved upon and/or to compete with you). Likely
  8. 8. 6must-have core capabilities include: • Performance (e.g., fast screen refresh) • Offline capability (i.e., ability to work when not connected to the Internet) • Location awareness (e.g., the data/experience will change with the user’s location) • Cloud syncing (e.g., users see the same data on multiple devices) • Push notifications (i.e., sending updated information to devices as soon as it is available)When you have a handle on what your app does, the next step is todesign it. Designing your app involves making choices of how infor-mation and controls are presented to the user as well as how toimplement app logic, and figuring out what data lives locally andwhat belongs in the Cloud.
  9. 9. 3Design your app
  10. 10. 8Design your appUser experience decisions determine the app’s look and feel. Theyanswer questions such as: What does the app look like? What screensdoes it have? In the software development world, onscreen objectslike buttons, sliders, and fill-in boxes are called widgets. So you needto decide which types of widgets will reside on which screens. Andwhat actions will occur as a result of the user interacting with thosewidgets?Keep in mind that users will expect to interact differently with amobile device than they do with a PC because the screens on mobiledevices are much smaller. They’ll expect to use their fingers insteadof a mouse or a track pad. Ideally, your app can even be used withone hand holding the device whileusing just a thumb for scrolling andworking the app’s other controls — thePath app is a good example, and “ Your app’sincreasingly, so is Facebook. features will inform its archi-Your app’s features will inform its tecture, which isarchitecture, which is how you’ll divide how you’ll dividethe code and data into functional parts. the code and dataIf your app requires interacting with into functionalother app users or networked services, parts.”you’ll need to figure out what piece ofthe logic lives in the app code and whatcomes from the backend. For example,your app might integrate with a restau-rant recommendation engine, shareuser location, or pull real-time traffic data. This is done using APIsprovided by various service providers — but you don’t have to wireup your app to a network to get started. You can develop a prototypeusing predefined representative (or “dummy”) data. It’s easier tofine-tune the front end if you don’t have to simultaneously modifyyour backend too. Once you get the app’s look-and-feel right, thenmake those backend connections.
  11. 11. 9Once you’ve got the overall concept for your app, the next step is toexpress that design in terms of the iOS app architecture. That archi-tecture is the model for what parts an iOS app can contain and howthose parts fit together. It’s a well thought-out approach for translat-ing a product concept into actual code you can deploy on a device.WHY iOS?Besides the features and design of your first app, there’s one moredecision you need to make before you start actual development.That’s whether to deploy on Apple’s iOS platform or on Google’sAndroid platform. (Some of this is also covered in our ebook, How toMake an App: Android Edition.) Reasons to develop for iOS include: Why iOS? $ {-X-} $$ Customers more The Apple All-in-one The Apple Tablets willing to pay ecosystem IDE experienceCustomers more willing to pay. Perhaps it’s because of Android’sopen source heritage, but whatever the reason, Android apps gener-ate less than 10% of the total dollars spent on mobile apps, despitehaving 75% of the smartphone market itself — and despite the factthat the average selling price of an app in the Google Play is $3.79versus Apple App Store’s $2.01. In other words, Apple users are muchmore willing to spend money on apps.The Apple Ecosystem. Some developers and users prefer Apple’sclosed and more tightly controlled environment. Apple’s ecosystem,consisting of Xcode, iCloud, iTunes, the App Store, the iPad, theiPhone, Mac computers, etc., offers a very holistic user experiencewith the ability to share data seamlessly across devices plus the
  12. 12. 10assurance of having applications pre-approved for quality andcontent prior to going on sale.Xcode. Apple’s all-in-one IDE offers state-of-the-art offers features likea graphical interface builder and a syntax-aware and compiler-awaresource editor.The Apple Experience. From the fit and finish of its hardware to thecustomer service in its retail stores, to the way its hardware andsoftware work flawlessly together, Apple has created the premiumbrand in consumer electronics. iOS developers share the benefits —so when someone downloads your iOS app, they already expect it’s agreat product. And that it will also work flawlessly on their device.Tablets. iOS has a clear advantage over Android in terms of tabletmarket adoption. Using Xcode, it’s also much easier to migrate anapp from a phone to a tablet and vice versa than it is when develop-ing for Android.Why Not iOS?Although iOS offers many compelling advantages as a platform foryour mobile app, it also comes with some disadvantages. Here arethree: Why NOT iOS? Closed Market Approvals platform growthClosed Platform. iOS apps only run on Apple products so you can’ttake advantage of features (like NFC) available only on non-iOSdevices or market growth of non-iOS devices.
  13. 13. 11Market Growth. Today, iOS represents less than 15% of the totalsmartphone market, Although the total market (“the whole pie”) isstill increasing at a fast rate, Android market growth outpaces iOSgrowth.Approvals. The App Store’s app approval process is notoriously moretime consuming than Google Play’s process. iPad vs. iPhone Of the over 700,000 iOS apps available in the App Store, 250,000 of them are specifically for iPad. Whether you develop for iPhone or iPad depends on a number of factors, including: Screen Size. Most people do not want to watch a movie or read a book on a smartphone, so if your app is better suited for a larger screen, you should consider iPad. Portability. On the other hand, if your app is something people are likely to use when they are “out and about,” such as when shopping, then iPhone may be your primary target. Media. Because it is more portable, iPhone is a better device for taking pictures and video while iPad offers a better viewing and editing experience (again, because of screen size). Consuming or Creating? As in the editing case, if your app is more about working with content than consuming it, you probably are better off developing for iPad.
  14. 14. 12 Getting your app approvedLet’s say you’ve already made your iOS app, and it works great.Now “all” you need to do is get it approved by Apple so yourapp can go on sale in the App Store. Don’t underestimate theimportance of this step or the level of effort that may berequired. In fact, the best time to familiarize yourself withApple’s App Store requirements is before you start makingyour app. Fortunately, a number of very helpful resources areavailable online to assist you. Here are four we recommend: 1 Apple’s App Store Submissions Tutorial 2 Apple’s App Review Guidelines 3 Apple’s iOS Human Interface Guidelines 4 Kinvey blog article, “6 Ways to Ensure App Store Approval”
  15. 15. 4The iOS app architecture
  16. 16. 14The iOS app architectureAs noted earlier, a key reason why there are so many apps for iOS isbecause developing highly functional, polished apps for the platformis relatively easy. That’s mainly because of: 1) the design of thedevelopment tools, and 2) the key architectural features most iOSapps have in common. So let’s start with some concepts since it helpsto know what goes into an app before trying to create one. We’llbegin with: • Design patterns • Frameworks • Delegation • Storyboard • Windows • Outlets • Supporting files • ProductsDesign patterns. iOS apps implement what is known as a Mod-el-View-Controller (MVC) pattern. A pattern is a common way tostructure code that solves a particular design problem. The MVCpattern separates application code in a way that allows you to easilychange one part of an app without having to change other parts. AnMVC pattern consists of three components: • The Model is the logic that acts on the data, such as to store or retrieve data from a database, compute the distance between two cities on a map, etc. An example of a model is the Kinvey backend that stores your data in the Cloud as a service. • The View provides the interface to the user; it displays the data and widgets (e.g., buttons and text fields) that allow the user to interact with the data. An iPhone app may have more than one view, as in the Contacts app, which displays a list view of all contacts or alternatively a view of each individual contact. • The Controller is between the model and the view — i.e., it responds to user requests (made in a view) and retrieves results
  17. 17. 15 (produced in a model). This is where developers spend most of their time — constructing the View Controller — by defining and attaching actions (or behaviors) to onscreen widgets. When the user taps a button, for example, it is the View Controller that determines what action will occur, such as retrieve stored data from your Kinvey-based data store. The link between a view object (like a button) to a controller action is called a connection.Frameworks. You don’t actually have to write most of an app’s logic. Italready exists as frameworks. A framework is a collection of classesthat implements some function — such as connecting to the Internet,drawing a button, etc. Rather than write the code from scratch, youjust use the frameworks supplied by iOS. Some frameworks areautomatically present when you start a new project while others mayneed to be added (done via a drop down menu in Xcode’s ProjectEditor).Delegation. Say, you want to customize the behavior of a framework’sobject. You can’t actually modify the code of the framework classitself (prohibited since other apps may also use the framework). Butwhat you can do is provide app-specific behavior in an applicationdelegate object. If a delegate implements a method, it will be calledby the delegating class to modify its behavior. In the Kinvey sampleapp (one of two examples we will be describing below), the AppDele-gate.h and AppDelegate.m — the header and implementation filesfor the UIApplicationDelegate, respectively — contain the code thatauthenticates an app to the Kinvey backend service.Storyboards and XIBs. The MainStoryboard.storyboard file (or a .xibfile, if you did not click on the “Use Storyboard” option when startingyour project) contains the view information needed to implement theoverall flow and display of your application and the user interfaceelements.Windows. Each view (e.g., the contact list and individual contactdetails in the Contacts app) exists within a window. The windowrepresents the entire device screen and is where all your views arepresented.
  18. 18. 16Outlets. A variable by which a view object can be referenced in acontroller. (For example, if you place a text field to capture a usersname, you might create an outlet called UITextField* nameField.)Supporting files. These are files that provide resources (like PNGimages and other static data) that your app needs as well as files thatconfigure how the app will run. Other examples: .pch files — precompiled headers used for the code files in your project. .plist files — property lists that are small amounts of persistent data (like your app’s default user settings) consisting primarily of strings and numbers that you want your app to be able to access, modify if needed, and write back into the property list. main.m file — your app’s main function. This is needed to launch the app, but you will not need to modify this file. InfoPlist.strings file — used for localization.Products. This is the file for your app (i.e., YourProduct.app) that isbuilt when you click Xcode’s “run” button.“Making an iOS app” involves working with these features in thetypical, straightforward workflow: • Storyboard your views by dragging and configuring graphical • objects on a template • Adding behaviors to the various widgets Writing the classes as to define those behaviors (including • delegates) • Adding needed support files • Building and running the app Iterating until you are satisfied with your appThis is all done within Xcode.
  19. 19. 5What’s Xcode?
  20. 20. 18What’s Xcode?You can start developing functional, good-looking apps almost fromthe moment you download Xcode, Apple’s integrated developmentenvironment (IDE) for making iOS and Macintosh apps. Among otherfeatures, Xcode includes a source code editor, graphical user inter-face (GUI) editor (sometimes called Interface Builder), source coderepository manager, compiler, and much more. iOS applications aretypically developed by manipulating views graphically and by typingObjective-C code for the models and controllers.To get Xcode, simply go to the App Store and download the applica-tion (it’s free). To do this, click on the App Store icon in your Mac’sdock, or visit https://itunes.apple.com/us/genre/ios/id36?mt=8The app store will download and install Xcode in your Applicationfolder. From Applications, double-click the Xcode icon to launchXcode and you’ll see its splash screen (Figure 1). From there you canclick on “Create a new Xcode project” to take you to a menu of severaltemplates on which to base your application. Selecting a templateopens an Xcode workspace pre-populated with frameworks andother files Xcode thinks you will need using that template.fig. 1 Xcode welcome screen. Create a new project from here.
  21. 21. 19Although you can develop, build and simulate your app on yourcomputer in Xcode, you can’t run your app on a target device (evenyour own iPhone) until you become a registered iOS developer andjoin the iOS Developer Program. To do that, go to develop-er.app.com/ and navigate to the iOS Dev Center. While there, you willalso find documentation, sample code and other useful resourcessuch as information on how to submit your app to the iOS App Store. fig. 2 The Xcode interfaceEverything you do in Xcode is done in a window, called a workspace(Figure 2), consisting of multiple work areas, some of which are alsodivided into panes. All the files needed to build your app belong to aproject, and the Navigator area (far left) lists all your projects (therecan be several in a workspace) and all files for each project. Clickingon a file in the Navigator area shows its contents in the Editor areaand invokes the appropriate editor. Clicking on a .h or .m file, forexample, shows the file’s source code and invokes the Source editor,so you can edit the code. Clicking on .storyboard or .xib (sometimescalled a “nib”) file shows the app’s storyboard and invokes the Inter-face Builder, so you can design a view using the Builder’s drag anddrop features.An especially handy feature is that the Editor area can have both aright and a left pane — with each pane aware of your edits in theother. So, for example, you can simultaneously edit an object’s .h
  22. 22. 20header file in the left pane and its corresponding .m in the right pane.Or you might click on a button object (displayed graphically) in theleft pane and edit its method’s source code in the right pane. Totoggle between a single pane (the “Standard Editor”) and double paneview (the “Assistant Editor”), use the Editor selector button on theright of the toolbar. You can option+command+click a symbol in theeditor to open the definition in the opposite editor pane.You can also resize the entire Editor area simply by dragging itsborders. For even more editing space, you can also remove the Debugarea or both the Debug and Utility areas using the View Selectorbutton on the far right of the toolbar. As its name suggests, the Debug area shows information, like variable state and console logs, helpful in debugging code. “...you can’t run your app on a The Utility area has two panes: the target device Inspector and Quick Help pane (top) and until you become the Library pane (bottom). Although a registered iOS there are five inspectors — File, Help, developer... ” Identity, Attributes, Size and Connec- tions — only the inspectors that are currently relevant appear in the Inspec- tor list at the top of the pane. (To see the name of an inspector, move the cursor over its icon in the Inspector selector bar.)You will use inspectors to add and modify object attributes for viewsin the Interface Builder. For example, if you click on a UILabel in theEditor area of a storyboard, you can use the Attributes inspector tochange the label’s color and use the Size inspector to change thelabel’s size.The Help inspector shows help information about a selected class.Use the Identity inspector to view and manage an object’s metadatasuch as its class, runtime attributes, label and so forth. Use the
  23. 23. 21Connections inspector to view the outlets and actions of an interfaceobject, to make new connections and to delete existing connections.The Library pane has libraries of resources (like file templates, codesnippets, interface objects and media files) that are prebuilt andready to insert into your project. Use the Library selector to selectwhich of these libraries (e.g., code snippets or interface objects) youwish to insert. To insert one, drag it directly into your storyboardwhile using the Interface Builder editor.These are basics you need to know to get started using Xcode tobuild your first app. But to really understand how it’s done, it helps towalk through an actual app or two. Let’s start with a simple “HelloWorld” app that does not employ a backend connection, and thenlook at a somewhat more functional app that does.
  24. 24. 6“Hello World!” sample app
  25. 25. 23“Hello World!” sample appThis app displays a button (“Press Me”) and a label (“Label”) so thatwhen the user presses the button the text of the label changes to“Hello World!” as in Figure 3: fig. 3 Clicking on the “Press Me” button displays “Hello World!”To get started, launch Xcode and select “Create a New Xcode Project.”From the iOS Application templates, select “Single View Application”and click “Next.” Fill in your product’s name and a company identifier,typically “com.yourCompanyName.” Deselect “Use Storyboards” andleave “Use Automatic Reference Counting” selected. Then click “Next”and select a destination for your projects files. fig. 4 Create a view with a label and a button
  26. 26. 24 1Follow these steps to make your app: 1. Select your project’s ViewController.xib file in the Navigator (Figure 4), to open the Interface Builder editor. 2. Drag a “Round Rect Button” from the Objects library (lower right) onto the view in the Editor area; select the button’s text and type “Press Me.” 3. Drag a Label from the objects library onto the view, as well. 4. Select and drag the Label sizing handles, centering the object and making it wide enough to hold the “Hello World!” text; then,fig. 5 Align a label in the attributes inspector 5. With the “Hello World!” label still selected, click on center alignment in the Attributes inspector. 6. Open the Assistant Editor (Figure 5), exposing the source code header file (ViewController.h) of the view controller you just built graphically. 7. Select the button and control-drag from the button to just below the ViewController definition in the Assistant panel. In the form that opens, select “Action” for the connection type, type in a name (“showText”) and click “Connect.” This creates an interface builder (IB) action as highlighted in Figure 6.
  27. 27. 25fig. 6 Connect the button’s Touch Up Inside event to an action in the ViewController 8. Next step is to create an outlet for the label. To do this, select the label object and control-drag from the label to just below the IB action you just created. Select “Outlet” as the connection type and enter a name “label” and click “Connect.” This creates an interface builder (IB) outlet as shown in Figure 7.fig. 7 Connect the label to the ViewController as an outlet
  28. 28. 26 9. Finally, it’s time to add some logic to the view controller so it knows what to do when the button is pressed. To do this, select “ViewController.m” in the project navigator to show the code editor. Find the button’s IBAction you just created (near the bottom), place your cursor between the { } brackets and hit the return key a few times to create some extra space. Then in that space type the method for how you want the label you speci- fied to respond: _label.text=”Hello World!”; as highlighted in Figure 8.fig. 8 _label.text = "Hello World"; will set the label text on the button press.Congratulations! Your app is done. To build and run your new app inthe simulator, click the Xcode Run button in the left corner of thetoolbar. When you click the button, the text will update.
  29. 29. 7Sample app with a backend
  30. 30. 28Sample app with a backendThis second app (named “Kinvey Test Drive”) lets the user type texton an iPhone and save the text to a backend service, like Kinvey. Italso lets the user load text on the iPhone from their Kinvey backend.Reading about this app will help you learn: • How to set up Kinvey’s library in an iOS project • Additional Interface Builder techniques you can use to story- board an application • How to add view controller logic to interact with the backend service, allowing you to save and retrieve dataWe will first present the app as a running application and then take itapart so you can see how it was made. To make the app yourself, youcan review the various sections below and replicate the steps in yourcopy of Xcode.First, to see the app in action, you should download the app and runit on your system. To do that, sign up for Kinvey, then navigate to“Dev Center”, “Samples,” find the “Test Drive” app, and click on itsicon. (If you can’t find it right away, make sure you select iOS as yourplatform on the right side of the menu bar.) Click the downloadbutton to download the app’s project files to your computer. Thenlaunch Xcode — just double click on the .xcodeproj file in the projectfolder.But before you can run the app, you need to set up the app’s Kinveybackend.Set Up Kinvey as a Backend Data StoreTest Drive’s project files include all the code the sample app needs inorder to talk to Kinvey. However, that would not be the case if youwere to build an app from scratch — so you would have to gothrough an initial Kinvey setup procedure. This involves downloadingthe Kinvey library files from the downloads section of devcenter.kin-vey.com and dragging them to the Navigator’s Frameworks folder inXcode. You also need to tell Xcode to link your project with additionaliOS frameworks. To find these frameworks, click on the Project folder
  31. 31. 29 at the very top of the Navigator pane — which displays the Project editor — and then select the “Build Settings” tab. For detailed instruc- tions, complete the “Getting Started” page under “Guides” on the Kinvey website. But again, you can skip this setup procedure for now in order to run the downloaded Kinvey Test Drive app. But you must still do this step: To run any app that uses Kinvey (including Test Drive) you need to do the “Create an App” step on the Kinvey website. Click on “My Apps” in the Kinvey menu bar and then click on “Add an App,” which will open an “Add” page. Type in a name for your app and click on the Apple logo and then click “Create.” The page that opens shows your App’s credentials. Copy and paste the App Key and App Secret into the AppDelegate.m file of the download- ed Test Drive project:#import "AppDelegate.h"#import <KinveyKit/KinveyKit.h>@implementation AppDelegate- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions{ (void) [[KCSClient sharedClient] initializeKinveyServiceForAppKey:@"<#My App Key#>" withAppSecret:@"<#My App Secret#>" usingOptions:nil]; return YES;} You are now ready to run the app — click on the Xcode run button and wait for the simulator to open and the app to appear (Figure 9).
  32. 32. 30 fig. 9 fig. 10 fig. 11 fig. 12Test Drive App viewsClicking the “+” toolbar button opens an alert (Figure 10) with anempty field into which the user can type some text (e.g., “some newdata”). Clicking “save” uploads the data to Kinvey and displays text onthe screen (a table view) and also displays an alert that the saveworked (Figure 11).To test the load function, enter some data (e.g., “some data to load”)in the “name” field of the Kinvey collection. To see the load, the swipedown on the table on the phone until the refresh spinner starts, andthen the new data will appear in the table (Figure 12).Figure 13 shows the Kinvey collection after the save that Figure 10depicts on the iPhone. Figure 14 shows the Kinvey collection after theuser adds a new row to the testObjects collection using the webbrowser. Note that every time a save is done on the iPhone, Kinveyautomatically adds a new row (displayed on a collection refresh). Toadd a new row manually in the browser, click “+ row,” and type somedescriptive text in the “name” column. That data will now load on theiPhone when the user pulls down on the table.
  33. 33. 31fig. 13 Backend collection after saving from the appfig. 14 Backend collection after adding a new row directly.Storyboard the Test Drive AppMost of the Test Drive user interface objects visible in the simulationare available in Xcode’s Object Library and can therefore be added tothe view graphically. The UI objects consist of a: • Table view • Toolbar • Tool Bar Button item – flexible space • Tool Bar Button item – Add • Table view cell • Label – Title • Refresh Control
  34. 34. 32To create this app yourself, you would follow these steps: • Launch Xcode and select the “Single View Application” template • Select the “Use Storyboard” option • Replace the default UIviewController object with a UITableView- Controller • Drag and drop the other objects, in the order listed, onto the UIviewcontrollerAlso note: • The Flexible Space Bar Button item fills up the space on the toolbar so the add button is at the right. This is a standard pattern in table-based iPhone apps. • The add button shows the system “+” sign. That is done by dragging a bar button item onto the toolbar, clicking on the Identifier drop down menu in the Attributes inspector; and then selecting the “Add” option.As with the “Hello World!” app, once your app’s view is complete(Figure 15), you would still have to create the various methods andconnections that bring them to life. This is done using the Sourceeditor while working with the ViewController.m file. fig. 15 Editing a table in Interface Builder.
  35. 35. 33Add View Controller LogicSince the app performs two basic operations (save data to Kinvey andload data from Kinvey) these two methods must be added to theViewController header file. That’s done with a control-drag from the“+” bar button over to just under the “@interface ViewController”line in ViewController.h. (Open the Assistant editor to see both thestoryboard and the file source.) fig. 16 Drag an add: action from the button bar to the ViewController header fileDuring the drag, the popup appears, asking for the name and type ofconnection. Enter “action” for the connection type and “add” for thename. Then repeat the drag, this time from the refresh control andusing “load” for the name (Figure 16). Note: to follow this discussion it will help to have the referenced files open in your Xcode Source editor.In ViewController.m, you will see the implementation code associatedwith each of the two Interface Builder methods, whose names Xcodeadded automatically to the .m file:- (IBAction)add:(id)sender- (IBAction)load:(id)senderYou will also see a third section of code not associated with thesemethods, which starts with the line: “#pragma mark - Table ViewStuff” These methods support the table view and are part ofUITableViewD-elegate and UITableViewDataSource. They handlecontrolling the
  36. 36. 34display of the table, and respond to user gestures. For example,swiping a table cell will show the delete button because tableView:-canEditRowAtIndexPath: returns YES and tableView:editingStyleForRowA-tIndexPath: returns UITableViewCellEditingStyleDelete. If you tap thedelete button, the delegate method tableView:commitEditingStyle:for-RowAtIndexPath: is called. The code of this method deletes the datafor the row and removes it from Kinvey’s data store. When thebackend delete is completed, the app displays an alert describing thesuccess or failure.The way that all three sections (and all Kinvey-enabled apps) movedata in and out of a Kinvey collection is by getting a reference to theapp’s backend collection (named “testObjects”), which is filled withinstances (each named “TestObject”) of the data the app wants tomove. That’s why you’ll find the following code repeated three timesin Test Drive’s View Controller (once for the add, once for the load,and once for the delete):KCSCollection *testObjects = [KCSCollection collectionFromString:@"testObjects" ofClass:[TestObject class]];KCSAppdataStore *store = [KCSAppdataStore storeWithCollection:testObjects options:nil];To support these statements it is required to have a data object class(TestObject). To see how these files are written in the sample project,click on TestObject.h file and TestObject.m in the Navigator pane. Ifyou were to supply these files in your own app, you would click File >New File, and specify Objective-C class, which would be a subclass ofNSObject. Then you would type in the code, with a property for eachcolumn in the Kinvey backend collection (including one for theobject’s id).As mentioned earlier, your app also needs to authenticate itself toKinvey, which is handled by AppDelegate.h and AppDelgate.m. Thesefiles are created by Xcode when you create a new project, and startout with just a stub implementation. Look in the sample app source
  37. 37. 35files for code to copy and paste.For both the save and load operations, however, moving the data inand out of a backend collection is only part of the work. Table 1 listsall the functions that implements the save and load in the ViewCon-troller.m file, along with pointers to its corresponding block of imple-mentation source code. (For each function, its corresponding codebegins with the “Starts at” line and ends with the “Ends at” line.) Referto Appendix 1 to find the actual source code.Say Hello To Our WorldThe key takeaway from all this is that “making an app” is a worthwhilething to do for anyone with a clever idea and a working knowledge ofObjective-C. The proof is in the hundreds of apps succeeding in themarket every day, many written by people working on their own andwho never wrote an app before in their lives. As with anything else,practice does make perfect. But hopefully with all the resourcesavailable, and the knowledge gained from this ebook, you havealready started down the path toward joining the growing legions ofiOS app developers. If so, we welcome you!Table 1: Save and Load Implementation Details of Kinvey Test Drive Sample App
  38. 38. 36 1 Appendix 1 — Test Drive Sample App ViewController.m Source Code//// ViewController.m// Kinvey Quickstart//// Created by Michael Katz on 11/12/12.// Copyright (c) 2012-2013 Kinvey. All rights reserved.//#import "ViewController.h"#import "TestObject.h"#define CREATE_NEW_ENTITY_ALERT_VIEW 100@interface ViewController ()@property (nonatomic, strong) NSArray* objects;@end@implementation ViewController- (IBAction)add:(id)sender{ UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Create a New Entity" message:@"Enter a title for thenew entity" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Save", nil]; alert.alertViewStyle = UIAlertViewStylePlainTextInput; alert.tag = CREATE_NEW_ENTITY_ALERT_VIEW; [alert show];}- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)but-tonIndex
  39. 39. 37{ if (alertView.tag == CREATE_NEW_ENTITY_ALERT_VIEW) { if (buttonIndex == alertView.firstOtherButtonIndex) { // Define an instance of our test object TestObject *testObject = [[TestObject alloc] init]; // This is the data well save testObject.name = [[alertView textFieldAtIndex:0] text]; // Get a reference to a backend collection called "testObjects", whichis filled with // instances of TestObject KCSCollection *testObjects = [KCSCollection collectionFromString:@"tes-tObjects" ofClass:[TestObject class]]; // Create a data store connected to the collection, in order to saveand load TestObjects KCSAppdataStore *store = [KCSAppdataStore storeWithCollection:testOb-jects options:nil]; // Save our instance to the store [store saveObject:testObject withCompletionBlock:^(NSArray *objectsOr-Nil, NSError *errorOrNil) { // Right now just pop-up an alert about what we got back fromKinvey during // the save. Normally you would want to implement more code here if (errorOrNil == nil && objectsOrNil != nil) { //save is successful! UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Saveworked!" message:[NS-String stringWithFormat:@"Saved: %@",[objectsOrNil[0] name]] delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
  40. 40. 38 [alert show]; self.objects = [@[testObject] arrayByAddingObjectsFromArray:_-objects]; [self.tableView insertRowsAtIndexPaths:@[[NSIndexPath indexPa-thForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic]; } else { //save failed UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Savefailed" message:[erro-rOrNil localizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } } withProgressBlock:nil]; } }}- (IBAction)load:(id)sender{ // Get a reference to a backend collection called "testObjects", which isfilled with // instances of TestObject KCSCollection *testObjects = [KCSCollection collectionFromString:@"testObjects"ofClass:[TestObject class]]; // Create a data store connected to the collection, in order to save and loadTestObjects
  41. 41. 39 KCSAppdataStore *store = [KCSAppdataStore storeWithCollection:testObjectsoptions:nil]; KCSQuery* query = [KCSQuery query]; [query addSortModifier:[[KCSQuerySortModifier alloc] initWithField:KCSMetadata-FieldLastModifiedTime inDirection:kKCSDescending]]; // This will load the saved 12345 item from the backend [store queryWithQuery:query withCompletionBlock:^(NSArray *objectsOrNil,NSError *errorOrNil) { [sender endRefreshing]; // Right now just pop-up an alert about what we got back from Kinvey during // the load. Normally you would want to implement more code here if (errorOrNil == nil && objectsOrNil != nil) { //load is successful! _objects = objectsOrNil; [self.tableView reloadData]; } else { //load failed UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Load failed" message:[errorOrNillocalizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } } withProgressBlock:nil];}#pragma mark - View Controller- (void)viewDidLoad
  42. 42. 40{ [super viewDidLoad]; _objects = @[]; [self.refreshControl addTarget:self action:@selector(load:) forControlEvents:UIControlEventValueChanged];}- (void)viewWillAppear:(BOOL)animated{ [super viewWillAppear:animated]; [self load:nil];}#pragma mark - Table View Stuff- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{ return 1;}- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ return _objects.count;}- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(N-SIndexPath *)indexPath{ UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"aCell"]; cell.textLabel.text = [_objects[indexPath.row] name]; return cell;}
  43. 43. 41- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath*)indexPath{ return YES;}- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleFor-RowAtIndexPath:(NSIndexPath *)indexPath{ return UITableViewCellEditingStyleDelete;}- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEdit-ingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{ if (editingStyle == UITableViewCellEditingStyleDelete) { TestObject* objToDelete = [_objects objectAtIndex:indexPath.row]; NSMutableArray* newObjects = [_objects mutableCopy]; [newObjects removeObjectAtIndex:indexPath.row]; self.objects = newObjects; [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UI-TableViewRowAnimationAutomatic]; // Get a reference to a backend collection called "testObjects", which isfilled with // instances of TestObject KCSCollection *testObjects = [KCSCollection collectionFromString:@"testOb-jects" ofClass:[TestObject class]]; // Create a data store connected to the collection, in order to save andload TestObjects KCSAppdataStore *store = [KCSAppdataStore storeWithCollection:testObjectsoptions:nil]; // Remove our instance from the store
  44. 44. 42 [store removeObject:objToDelete withCompletionBlock:^(NSArray *objectsOr-Nil, NSError *errorOrNil) { if (errorOrNil == nil && objectsOrNil != nil) { //delete is successful! UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Deletesuccessful!" message:nil delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } else { //delete failed UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Delete failed" message:[errorOrNillocalizedDescription] delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil]; [alert show]; } } withProgressBlock:nil]; }}@end
  45. 45. HOW TO MAKE AN APP: iOS EDITIONWritten by Designed byRandall Cronk Jake McKibben and Lauren PedigoSince 1990, Randall has helped over 250high-tech companies convey the value of Project Managerwhat they do through white papers, webcontent, brochures, case studies and Brian Whalleyarticles. Based today in downtownBoston, he was previously a vicepresident with Regis McKenna where heran the Digital Equipment account.Michael KatzMichael has always been a programmer.In college he detoured into modeling thebrain, but eventually found his way backinto software development, doinghard-core desktop Java programming.But since 2010, he has developed mobileapps and software. He is also the authorof a forthcoming iOS networking book,being published by Manning Publica-tions later this year. What is Kinvey? Kinvey makes a fully-featured Backend as a Service solution, offering 3rd party data integrations, multi-plat- form support, push notifications, and custom business logic on a platform where its free to get started and you only pay when your app is successful. Build your backend today

×