Friday, May 6, 2011

iOS - Architecture


Cocoa Touch Layer - features

Multitasking

Applications built using iOS SDK 4.0 or later (and running in iOS 4.0 and later) are not terminated when the user presses the Home button; instead, they shift to a background execution context. The multitasking support defined by UIKit helps your application transition to and from the background state smoothly.
To preserve battery life, most applications are suspended by the system shortly after entering the background. A suspended application remains in memory but does not execute any code. This behavior allows an application to resume quickly when it is relaunched without consuming battery power in the meantime. However, applications may be allowed to continue running in the background for the following reasons:
  • An application can request a finite amount of time to complete some important task.

  • An application can declare itself as supporting specific services that require regular background execution time.

  • An application can use local notifications to generate user alerts at designated times, whether or not the application is running.

Regardless of whether your application is suspended or continues running in the background, supporting multitasking does require additional work on your part. The system notifies your application as it transitions to and from the background. These notification points are your cue to perform any important application tasks such as saving user data.

Printing

Introduced in iOS 4.2, the UIKit printing support allows applications to send content wirelessly to nearby printers. For the most part, UIKit does all of the heavy lifting associated with printing. It manages the printing interfaces, works with your application to render the printable content, and handles the scheduling and execution of print jobs on the printer.
Print jobs submitted by your application are handed off to the printing system, which manages the actual printing process. Print jobs from all applications on a device are queued and printed on a first-come, first-served basis. Users can get the status of print jobs from the Print Center application and can even use that application to cancel print jobs. All other aspects of printing are handled for you automatically by the system.

Data Protection

Introduced in iOS 4.0, data protection allows applications that work with sensitive user data to take advantage of the built-in encryption available on some devices. When your application designates a specific file as protected, the system stores that file on-disk in an encrypted format. While the device is locked, the contents of the file are inaccessible to both your application and to any potential intruders. However, when the device is unlocked by the user, a decryption key is created to allow your application to access the file.
Implementing data protection requires you to be considerate in how you create and manage the data you want to protect. Applications must be designed to secure the data at creation time and to be prepared for access changes when the user locks and unlocks the device.

Apple Push Notification Service

Introduced in iOS 3.0, the Apple Push Notification Service provides a way to alert users of new information, even when your application is not actively running. Using this service, you can push text notifications, add a badge to your application icon, or trigger audible alerts on user devices at any time. These messages let users know that they should open your application to receive the related information.
From a design standpoint, there are two parts to making push notifications work for iOS applications. First, the application must request the delivery of notifications and process the notification data once it is delivered. Second, you need to provide a server-side process to generate the notifications in the first place. This process lives on your own local server and works with Apple Push Notification Service to trigger the notifications.

Local Notifications

Introduced in iOS 4.0, local notifications complement the existing push notification mechanism by giving applications an avenue for generating the notifications locally instead of relying on an external server. Applications running in the background can use local notifications as a way to get a user’s attention when important events happen. For example, a navigation application running in the background can use local notifications to alert the user when it is time to make a turn. Applications can also schedule the delivery of local notifications for a future date and time and have those notifications delivered even if the application is not running.
The advantage of local notifications is that they are independent of your application. Once a notification is scheduled, the system manages the delivery of it. Your application does not even have to be running when the notification is delivered.

Gesture Recognizers

Introduced in iOS 3.2, gesture recognizers are objects that you attach to views and use to detect common types of gestures such as swipes and pinches. After attaching a gesture recognizer to your view, you tell it what action to perform when the gesture occurs. The gesture recognizer object then tracks the raw touch events and applies the system-defined heuristics for what the given gesture should be. Without gesture recognizers, you must do all this work yourself, which can be quite complicated.
UIKit includes a UIGestureRecognizer class that defines the basic behavior for all gesture recognizers. You can define your own custom gesture recognizer subclasses or use one of the UIKit-supplied subclasses to handle any of the following standard gestures:
  • Tapping (any number of taps)

  • Pinching in and out (for zooming)

  • Panning or dragging

  • Swiping (in any direction)

  • Rotating (fingers moving in opposite directions)

  • Long presses

File-Sharing Support

Introduced in iOS 3.2, file-sharing support lets applications make user data files available via iTunes 9.1 and later. An application that declares its support for file sharing makes the contents of its /Documents directory available to the user. The user can then move files in and out of this directory as needed from iTunes. This feature does not allow your application to share files with other applications on the same device; that behavior requires the pasteboard or a document interaction controller object.
To enable file sharing for your application, do the following:
  1. Add the UIFileSharingEnabled key to your application’s Info.plist file and set the value of the key to YES.

  2. Put whatever files you want to share in your application’s Documents directory.

  3. When the device is plugged into the user’s computer, iTunes displays a File Sharing section in the Apps tab of the selected device.

  4. The user can add files to this directory or move files to the desktop.

Applications that support file sharing should be able to recognize when files have been added to the Documents directory and respond appropriately.

Peer-to-Peer Services

Introduced in iOS 3.0, the Game Kit framework provides peer-to-peer connectivity over Bluetooth. You can use peer-to-peer connectivity to initiate communication sessions with nearby devices and implement many of the features found in multiplayer games. Although primarily used in games, you can also use this feature in other types of applications.

Standard System View Controllers

Many of the frameworks in the Cocoa Touch layer contain view controllers for presenting standard system interfaces. You are encouraged to use these view controllers in your applications to present a consistent user experience. Whenever you need to perform one of the following tasks, you should use a view controller from the corresponding framework:
  • Display or edit contact information—Use the view controllers in the Address Book UI framework.

  • Create or edit calendar events—Use the view controllers in the Event Kit UI framework.

  • Compose an email or SMS message—Use the view controllers in the Message UI framework.

  • Open or preview the contents of a file—Use the UIDocumentInteractionController class in the UIKit framework.

  • Take a picture or choose a photo from the user’s photo library—Use the UIImagePickerController class in the UIKit framework.

  • Shoot a video clip—Use the UIImagePickerController class in the UIKit framework.


External Display Support

Introduced in iOS 3.2, external display support allows some iOS-based devices to be connected to an external display through a set of supported cables. When connected, the associated screen can be used by the application to display content. Information about the screen, including its supported resolutions, is accessible through the interfaces of the UIKit framework. You also use that framework to associate your application’s windows with one screen or another

Thursday, May 5, 2011

Reading and Writing plists

Reading a plist file from the application bundle just requires a few lines of code, and some error handling. I like to place that code in a nice convenience method like this:
 

- (id)readPlist:(NSString *)fileName {
   NSData *plistData;
   NSString *error;
   NSPropertyListFormat format;
   id plist;

   NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
   plistData = [NSData dataWithContentsOfFile:localizedPath];
   plist = [NSPropertyListSerialization propertyListFromData:plistData mutabilityOption:NSPropertyListImmutable format:&format errorDescription:&error];
   if (!plist) {
      NSLog(@"Error reading plist from file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
      [error release];
   }

   return plist;
}

I’m not too fond of using id as return values or parameters to methods. I prefer stronger type checks, so I typically wrap the readPlist method in two methods that return either an array or a dictionary.



- (NSArray *)getArray:(NSString *)fileName {
   return (NSArray *)[self readPlist:fileName];
}

- (NSDictionary *)getDictionary:(NSString *)fileName {
   return (NSDictionary *)[self readPlist:fileName];
}

Writing to a plist file is not much more difficult:

- (void)writePlist:(id)plist fileName:(NSString *)fileName {
   NSData *xmlData;
   NSString *error;

   NSString *localizedPath = [[NSBundle mainBundle] pathForResource:fileName ofType:@"plist"];
   xmlData = [NSPropertyListSerialization dataFromPropertyList:plist format:NSPropertyListXMLFormat_v1_0 errorDescription:&error];
   if (xmlData) {
      [xmlData writeToFile:localizedPath atomically:YES];
   } else {
      NSLog(@"Error writing plist to file '%s', error = '%s'", [localizedPath UTF8String], [error UTF8String]);
      [error release];
   }
}


Creating a New Navigation-Based Application

Open Up Xcode



You will be doing all of your development in Xcode. Then close the Welcome window (if it shows up)
Start a new iPhone OS Project
Click Xcode > New Project and a window should pop up like this:



Make sure Application is selected under iPhone OS and then select Navigation-Based Application. Click Choose… It will ask you to name your project.  Type in “Hello World” and let’s get started.

iPhone Programming Tutorial – UITableView Hello World

In this tutorial I will walk to you through creating a simple “Hello World” application using a UITableView for the iPhone.  There are many ways that a Hello World program could be made on the iPhone, I am going to show you the simplest.  This tutorial assumes you have a basic understanding of Objective-C.  Apple has provided a very simple and straight forward tutorial on Objective-C.  You can find it here.
You will learn how to:
This tutorial assumes that you have already installed the iPhone SDK.  If you are unsure how to do this, click and follow the steps.

Debugging Tutorial – Automating Your Tests With A UIRecorder Instrument

If you have ever experienced a bug in your application that took many steps to reproduce, then this tutorial is for you.  By nature, testing and debugging are very tedious processes.  This is especially the case for the iPhone.
Say you have an app that drills down 5-levels deep to some other view.  Now let’s say that you have a bug on that view 5 levels deep.  Your normal method of debugging is:
  • Run the app
  • Tap view 1
  • Tap view 2
  • Tap view 3
  • Tap view 4
  • Tap view 5
  • (Crash)
  • Change some code
  • Repeat
As you can see (and I’m sure have noticed), this sucks.  Well, Kendall Gelner gave a killer talk at 360iDev (which I recently attended) on various debugging tips using Instruments and XCode.  One of the most useful techniques (to me) was how to automate your testing.  Let me show you what I mean.

1. Open up the app you wish to test/debug
2. Launch it in the simulator
3. Open Instruments – This is located in /Developer/Applications/Instruments (just do a spotlight search for it)

screenshot_01

4. Select UIRecorder and click Choose - You should now see a window like this

screenshot_02

5. Now, we need to attach this tool to the iPhone Simulator process.  Click the drop-down above  

Default Target -> Attach to Process -> iPhone Simulator.


ss_03

6. Now click Drive & Record and do all of the steps in the simulator to test your app.  At this point, the UI Recorder is recording your every move.  When you have finished press the Stop button. Note: After you have recorded your actions, don’t move the simulator as it will mess up the entire process.
7. Modify your code…
8. Press the Drive & Record button and watch the magic happen.  The test is automatically done for you.  You should see your mouse move over to the simulator and the system mimicking every action that you did before.
That’s it! I know this isn’t a super long tutorial (or even a coding tutorial), but the UI Recorder has sped my test time up tremendously.  Give it a shot and let me know what you think.  Here is a short video of me going through all of the steps.

video tutorial

simple Navigationbased tutorial

It’s time to start displaying some drinks. You’ll need to make some modifications to both the RootViewController.h and RootViewController.m files

1Declare the drinks array.(in RootViewController.h )

@interface RootViewController : UITableViewController{
NSMutableArray* drinks;
}
@property (nonatomic, retain) NSMutableArray* drinks;
@end
(RootViewController.m)

@synthesize drinks;
-(void)dealloc{

[drinks release];

[super dealloc];

}

2 Implement and populate the array.(in RootViewController.m)
In RootViewController.m, uncomment and expand the ViewDidLoad methods.
Tell the table how many rows you have.
Populate the table cells.

- (void)viewDidLoad { [super viewDidLoad];
RootViewController.m
NSMutableArray* tmpArray = [[NSMutableArray alloc]

initWithObjects:@”Firecracker”, @”Lemon Drop”, @”Mojito”,nil];
self.drinks = tmpArray; [tmpArray release];
// Uncomment the following line to display an Edit button in

//the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self. editButtonItem;
}



3 Tell the table how many rows you have.

//Customize the number of rows in the table view.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return [self.drinks count];
 
4 Populate the table cells

// Configure the cell.
cell.textLabel.text = [self.drinks objectAtIndex:indexPath.row];

return cell;
}
 
Now you’re ready to go. Save it, build and run, and you’ll see the three drinks in your app in the main view.