2011年12月21日星期三

Basic Security in iOS 5 Tutorial Part 1

Basic Security in iOS 5 Tutorial Part 1

This is a post by Chris Lowe, an iOS application developer and aspiring game developer living in San Antonio, Texas. He warns that this tutorial is pretty Epic in length, but promises you’ll learn a thing or two along the way. :]
Learn how to store passwords securely in the Keychain!
Learn how to store passwords securely in the Keychain!
One of the most important aspects of software development also happens to be considered one of the most mysterious and scary (and is thus avoided like the plague): that of securing an application.
Users expect and demand that applications run as intended and keep their data safe and secure, whether it be from intruders, other users, or even from the correct user making mistakes.
But app security, while it can be time-consuming, need not be scary or mysterious!
Good app security has a couple of qualifications:
  • Users must not consciously know they are being protected. (That is, don’t get in the way! Users aren’t there to evaluate your data security practices; they want to use your app!)
  • Your security must be difficult to work around or break. (Nothing is impossible to hack, given enough time and horsepower.)
  • Don’t be Citibank.
Luckily for us, Apple has created several APIs for our use to help make our apps the best they can be. These include:
  • Secure text entry
  • An encrypted keychain
  • Great hashing algorithms; and
  • The Data Protection API.
In this tutorial, we’re going to cover all of this and more, as we build an application to keep track of the holiday presents that we are going to buy our friends and family. We’ll call it “Christmas Keeper.”
As an added bonus, we’re going to use TONS of awesome new iOS5 features, including Twitter, Storyboards, ARC, JSON, Alert Views, Static Table Views, and a simple Custom UI.
So keep reading to learn more – by the end of this tutorial series, you will be a better, more security-conscious developer!

Getting Started (Plus, a Little Housekeeping)

Launch Xcode and create a new project with the iOS\Application\Single View Application template. Fill out the template fields as follows:
ChristmasKeeperTemplate
  • Product Name: ChristmasKeeper
  • Company Identifier: the identifier that you use for your apps, in reverse domain notation
  • Class Prefix: leave this empty
  • Device Family: iPhone
  • Use Storyboard: yes, please
  • Use Automatic Reference Counting: Ditto
  • Include Unit Tests: this should be unchecked
Ok, we have our project setup with all of the default settings. This is a great start, but it doesn’t make our app great, so let’s make a few tweaks.
First, download the images we are going to be using and drag and drop them into the project.
Now on the Project Summary page, you should see that Xcode already picked up the Default and Default@2x.png files for your splash images. Drag the Icon.png and Icon@2x.png files into their respective App Icons boxes (Xcode will complain about the images, but just click Yes).
CKSettings
While we are on this screen, scroll down (expand if necessary) to the Linked Framework and Libraries section. Go ahead and add the Twitter and Security Frameworks here.
CKFrameworks
Jump over to the Info tab (at the top of the Project Settings). Expand the “Icon Files (iOS 5)” option and the Primary Icons option. Take a second and change “Icon already includes gloss effect” to YES.
In Xcode 4.2/iOS5, Apple decided that you could have some icons with and without icon gloss so the generic item of “Icon already includes gloss effect” – that you would put as a new key on the root level – no longer applies.
Also, while you’re here, change the “Bundle Display Name” to something more friendly, like “Christmas” for example, or even something more sneaky like “Boring App” to throw off any spies. :]
Lastly, add a new key (by selecting the last entry and clicking the + button that appears). Select “Status bar is initially hidden” from the drop down, make sure the type is set to BOOL, and set it to YES. This will give us maximum screen real estate for our app.
CKInfo
Our tweaking here is done! Go ahead and hit Build and Run to make sure we didn’t fudge anything.
Christmas Keeper Launch Image

Storyboard Magic

One of the coolest parts of iOS5 is Storyboards. With it, we can mock up an entire application in a matter of minutes and, best of all, we don’t have to deal with the Application Delegate, Navigations Controllers, Tab Bar Controllers, or any other messy stuff that can waste a lot of development time!
So let’s head into the MainStoryboard.storyboard file and dig in. We are going to spend a bit of time here, so bear with me. It will be well worth it!
This is what our app is going to look like:
CKStoryboard
The default Storyboard is kind enough to give us a blank UIViewController to start with, so let’s be gracious hosts and use it! This view will serve as our landing view when the app is launched, and will be where we prompt the user for their PIN.
Add a UIImageView to the Controller and let it expand to the size of the window. If you happen to have a status bar still showing, snip that by going to the Attributes Inspector and changing the Status Bar Simulated Metric to None.
Set the image on the UIImageView to Default.png. iOS should auto-detect if you are on the Retina Display and change the graphic for us, since one is available.
CKLaunchImage
Next, drop a UITableViewController onto the Storyboard. It’s kind of ugly and it needs a title. So let’s put it in a Navigation Controller!
Do this by using the new “Embed In…” feature of Interface Builder. With the Table View selected, go to Editor menu > Embed In… > Navigation Controller. You’ll notice that a new Navigation Controller is added and automatically linked to the Table View.
CKEmbedIn
Now, let’s spice it up a little bit with some color. Select the Navigation Controller, then the Navigation Bar (you have to be zoomed in to 100% level to select it) and change its tint to green (you might need to select the Table View before its Nav Bar will pick up the color change). Then select the Navigation Bar on the Table View and set its title to “Christmas Presents.”
CKNavTitle
Let’s hook up the first View Controller we made with the new Table View. Control-Drag from the first View Controller (the one with the Image View on it) to the Navigation Controller. You can also drag it to the Table View Controller but I find it easier to understand this way.
Select Modal as the Segue type, then select the newly created Segue and change its transition style to Cross Dissolve. Set the Identifier as “ChristmasTableSegue.”
We’re going to create a custom Table View cell right inside of the Storyboard, and we’re going to use the one that is already provided for us from when we dropped in the UITableViewController. Select the white box below the “Prototype Cells” header and set the height to 90px. Set the Identifier to “ChristmasListCell,” and the Accessory type to Disclosure Indicator.
CKTableCell
Now drag a UIImageView onto the cell. Set the width and height to 90px, move it to the left corner (you’ll see all of the nice blue alignment lines appear), set the Image to “present.png”, and set the View Mode to Aspect Fit.
Then add a UILabel next to the image and set the width to 202 and the height to 90 (this should fill in nicely from the edge of the image to the Disclosure Indicator, again with the alignment lines appearing). Set the number of lines to 0 and set the font to custom, Helvetica Neue Light, size 14.
One last quick step here: add a UIBarButtonItem to the Navigation Bar on the Table View and set it to the “Add” Identifier.
CKCellArrows
Ok, take a breath. Blink a few times. We have a few more steps, and then our UI will be DONE! All thanks to the power of Storyboards!
Drag out another UITableViewController and embed it inside of a Navigation Controller, just like the last one. Set the Tint on this Controller as well. Maybe a nice festive red would fit the bill?
Next, create a Segue from the + (Add) UIBarButtonItem you added to the Christmas Presents Table and Control-Drag to the new Navigation Controller. Use a Modal action again, except leave the default Transition Style (we want it to pop up like normal). Set this segue’s Identifier to “AddChristmasPresent.”
Give the new UITableViewController a title of “New Present” and add “Cancel” and “Done” Bar Button Items.
Now, select the entire Table View, set it to Static and of type Grouped. It will give you three cells to work with, but we only need two, so delete one of the extras.
Select the first table cell, expand it to 236px, set the Identifier to NewPresentImageCell, and the Selection Style to None. Add a UIImageView to the cell, size 300×236; set the Aspect Fit and Image to “present.png.”
Select the second table cell, expand it to 156px, set the Identifier to NewPresentTextCell, and the Selection Style to None. Add a UITextView to that cell, size 300×156. Set the font to Custom, Helvetica Neue Light, size 14 here as well. Set the Return key to Done, and the default text to “Enter the details of your Christmas Present here!”
CKAddPresent
Finally, we want to view the presents that we have on the List. We want to view them in the same way that we added them, so we’ll cheat here and copy the “Add Present” Table View and reuse it as the “Present Details” Table View. To do that, click on the Table View Controller inside of the New Present Scene, and copy and paste it back into the Storyboard.
CKTableCopy
You’ll notice that it is pasted overtop of the Add Present Table View. Drag it off to its own spot and create a Segue from the Christmas Presents table cell to this view, selecting Push as the action. Set the Identifier to “ChristmasDetailsSegue.”
You should see the Table View pick up the existing Navigation Controller and color. Just a few changes needed here – remove the Cancel button, change the Done button to an Action button, change the title to “Present Details,” and uncheck “Editable” in the UITextView.
There, those are all of the changes you need to reuse the “Add Present” Table View as the “Present Details” Table View!
Lastly, hit Build and Run to make sure we didn’t break anything in the process. Of course, none of the transitions will work because we haven’t finished coding them yet, but we have the scaffolding in place!

Time To Code!

Enough with the Storyboard editor for now – let’s code something before we go cross-eyed hooking up Segues and tweaking table view cells! :]
We’ll start with the first View Controller that we tweaked in the Storyboard. Create a new file with the iOS\Cocoa Touch\UIViewController subclass template, name it ChristmasRootViewController, and make it a subclass of UIViewController. Leave the bottom two options unchecked.
Open ChristmasRootViewController.h and add a property for a BOOL that will tell us whether the user is authenticated. Call it “pinValidated.” Also, since we are going to be using several text fields in this class, go ahead and add yourself as a UITextField delegate ().
#import <UIKit/UIKit.h>
 
@interface ChristmasRootViewController : UIViewController <UITextFieldDelegate>
 
@property (nonatomic) BOOL pinValidated;
 
@end
Jump over to ChristmasRootViewController.m and synthesize the property we just created:
@synthesize pinValidated;
Next add the implementations for viewDidLoad and viewDidAppear:
#pragma mark - View lifecycle
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.pinValidated = NO;
}
 
- (void)viewDidAppear:(BOOL)animated 
{
    [super viewDidAppear:animated];
    [self presentAlertViewForPassword];
}
Two lines of code were added here. First we initialize our pinValidated property to NO. Then, once our view is on the screen, we call a method called presentAlertViewForPassword.
What does this do? Well, exactly as the method signature indicates, we are going to prompt the user for their PIN if they have one, or require them to set one up if they don’t. Add this above those two methods:
- (void)presentAlertViewForPassword 
{
 
    // 1
    BOOL hasPin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];
 
    // 2
    if (hasPin) {
        // 3
        NSString *user = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
        NSString *message = [NSString stringWithFormat:@"What is %@'s password?", user];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Enter Password" 
                                                        message:message  
                                                       delegate:self 
                                              cancelButtonTitle:@"Cancel" 
                                              otherButtonTitles:@"Done", nil];
        // 4
        [alert setAlertViewStyle:UIAlertViewStyleSecureTextInput]; // Gives us the password field
        alert.tag = kAlertTypePIN;
        // 5
        UITextField *pinField = [alert textFieldAtIndex:0];
        pinField.delegate = self;
        pinField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        pinField.tag = kTextFieldPIN;
        [alert show];
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Setup Credentials" 
                                                        message:@"Secure your Christmas list!"  
                                                       delegate:self 
                                              cancelButtonTitle:@"Cancel" 
                                              otherButtonTitles:@"Done", nil];
        // 6
        [alert setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
        alert.tag = kAlertTypeSetup;
        UITextField *nameField = [alert textFieldAtIndex:0];
        nameField.autocapitalizationType = UITextAutocapitalizationTypeWords;
        nameField.placeholder = @"Name"; // Replace the standard placeholder text with something more applicable
        nameField.delegate = self;
        nameField.tag = kTextFieldName;
        UITextField *passwordField = [alert textFieldAtIndex:1]; // Capture the Password text field since there are 2 fields
        passwordField.delegate = self;
        passwordField.tag = kTextFieldPassword;
        [alert show];
    }
}
This looks like a lot of code, but actually it’s quite simple. Let’s go over it step by step.
  1. First we check if the user has set up a PIN before. We do that by checking for a BOOL that we saved to the NSUserDefaults. Notice that we are checking for a key called PIN_SAVED. That seems kind of odd – it’s actually a macro from a Constants class we will get to in a moment.
  2. Then we evaluate if we have the BOOL or not. If we do, that means the user has launched this app before and gone through the setup process. If not, then the user hasn’t been here or setup the PIN before, so let’s prompt him again.
  3. Next we get the user’s name, also stored in NSUserDefaults, and then we ask “What is [your name here]‘s password?” Notice we also assign a value to alert.tag, from an enum also in the Constants class.
  4. A great new feature in iOS5 is that we now have multiple types of UIAlertViews at our disposal! Here we are going to use the UIAlertViewStyleSecureTextInput type, which simply gives us an alert view with a text field for entering a password.
  5. Another great new thing in iOS5: out of the box, we get access to the UITextFields that are shown in an alert view! No more hacks to navigate the view hierarchy, etc. Notice that the UIAlertView class now has a nice method for us called “textFieldAtIndex,” which gives us the UITextFields available to us! Also, we can do ANYTHING that you can do on a normal UITextField – here we are setting the delegate, the capitalization settings, and the tag.
  6. Like #4 above, we are going to use another new Alert View style, but this time have two text fields for a user name and password. Again, we can customize the UITextField to our liking. So, for example, you could set the keyboard type on the Password input if you want to restrict the password to numbers only.
OK, from here let’s create our Constants class (this will house all of our Macros, enums, etc.), update our Storyboard, then hit our first real Build and Run!
For the Constants class, create a new file with the iOS\Cocoa Touch\Objective-C class template, set the class as ChristmasConstants, and make it a subclass of NSObject. For this tutorial, we only need the .h, so you can delete the .m.
Then replace ChristmasConstants.h with the following:
// Used for saving to NSUserDefaults that a PIN has been set, and is the unique identifier for the Keychain.
#define PIN_SAVED @"hasSavedPIN"
 
// Used for saving the user's name to NSUserDefaults.
#define USERNAME @"username"
 
// Used to specify the application used in accessing the Keychain.
#define APP_NAME [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"]
 
// Used to help secure the PIN.
// Ideally, this is randomly generated, but to avoid the unnecessary complexity and overhead of storing the Salt separately, we will standardize on this key.
// !!KEEP IT A SECRET!!
#define SALT_HASH @"FvTivqTqZXsgLLx1v3P8TGRyVHaSOB1pvfm02wvGadj7RLHV8GrfxaZ84oGA8RsKdNRpxdAojXYg9iAj"
 
// Typedefs just to make it a little easier to read in code.
typedef enum {
    kAlertTypePIN = 0,
    kAlertTypeSetup
} AlertTypes;
 
typedef enum {
    kTextFieldPIN = 1,
    kTextFieldName,
    kTextFieldPassword
} TextFieldTypes;
Basically, all this file does is contain strings that we’ll use throughout the application.
We use enums here (remember our ChristmasKeeperRootViewController class) so that we can easily identify the Alert Type. We don’t have to remember that 0 means password only and 1 means username/password. The same goes for the TextFieldTypes enum.
Ignore the SALT_HASH meaning for now – we’ll get to that soon.
Now, go back to ChristmasRootViewController.h and import this class:
#import "ChristmasConstants.h"
Finally, jump back to the MainStoryboard.storyboard, select our first View Controller, and set its Class type under the Identity Inspector to ChristmasKeeperRootViewController (its likely still set to ViewController by default).
w00t – it’s finally time to BUILD AND RUN!!! When it starts up you should see a nice popup appear:
CKAlertSetup

Do Not Pass Alert View, Do Not Collect $200

So far so good, except there’s one small problem – it doesn’t do anything!
As you’ve probably surmised by now, we need to handle the user entering text input as well as hitting the buttons from the Alert View. Luckily, there is an easy fix to this problem – delegate methods!!
We get textFieldDidEndEditing: and alertView:didDismissButtonWithIndex: methods sent to us for FREE, and all we had to do was pay postage and shipping (and by that, I mean setting ourselves as the delegate).
Lets start with the Alert View delegate method. Add this inside ChristmasRootViewController.m:
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex 
{
    if (alertView.tag == kAlertTypePIN) {
        if (buttonIndex == 1 && self.pinValidated) { // User selected "Done"
            [self performSegueWithIdentifier:@"ChristmasTableSegue" sender:self];
            self.pinValidated = NO;
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    } else if (alertView.tag == kAlertTypeSetup) {
        if (buttonIndex == 1 && [self credentialsValidated]) { // User selected "Done"
            [self performSegueWithIdentifier:@"ChristmasTableSegue" sender:self];
        } else { // User selected "Cancel"
            [self presentAlertViewForPassword];
        }
    }
}
Remember that enum (enumerator for you more literal types) that we created from our ChristmasConstants class? Well, now it definitely comes in handy since we can easily (as reading humans) understand which Alert View we are talking about – just the password Alert View or the alert with username/password.
So first we check which view it is. Done. Then we check to see if the user hit the “Done” button AND if what was entered is correct.
If we fail that check, we prompt the user again for their credentials because we must authenticate someone. If we pass the check, however, we let them through. We do this via a performSegueWithIdentifier: sender: method, which will kick off our Cross Dissolve modal view that we created (way) earlier.
So now we have handled the Alert View. But “Wait!” you say. “How did we get pinValidated to YES, or validate the credentials the user entered?” The latter problem is simple to solve: we check for an existing username and password that has been written to the NSUserDefaults.
Add this right above alertView:didDismissWithButtonIndex:
// Helper method to congregate the Name and PIN fields for validation.
- (BOOL)credentialsValidated 
{
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    BOOL pin = [[NSUserDefaults standardUserDefaults] boolForKey:PIN_SAVED];
    if (name && pin) {
        return YES;
    } else {
        return NO;
    }
}
That takes care of the credentials check (used for first time setup), but what about pinValidated? This is where the textField delegate method comes in to save the day – and we finally get to see some security code!
Add the following method to ChristmasRootViewController.m:
#pragma mark - Text Field + Alert View Methods
- (void)textFieldDidEndEditing:(UITextField *)textField 
{
    // 1
    switch (textField.tag) {
        case kTextFieldPIN: // We go here if this is the 2nd+ time used (we've already set a PIN at Setup).
            NSLog(@"User entered PIN to validate");
            if ([textField.text length] > 0) {
                // 2
                NSUInteger fieldHash = [textField.text hash]; // Get the hash of the entered PIN, minimize contact with the real password
                // 3
                if ([KeychainWrapper compareKeychainValueForMatchingPIN:fieldHash]) { // Compare them
                    NSLog(@"** User Authenticated!!");
                    self.pinValidated = YES;
                } else {
                    NSLog(@"** Wrong Password :(");
                    self.pinValidated = NO;
                }
            }
            break;
        case kTextFieldName: // 1st part of the Setup flow.
            NSLog(@"User entered name");
            if ([textField.text length] > 0) {
                [[NSUserDefaults standardUserDefaults] setValue:textField.text forKey:USERNAME];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
            break;
        case kTextFieldPassword: // 2nd half of the Setup flow.
            NSLog(@"User entered PIN");
            if ([textField.text length] > 0) {
                NSUInteger fieldHash = [textField.text hash];
                // 4
                NSString *fieldString = [KeychainWrapper securedSHA256DigestHashForPIN:fieldHash];
                NSLog(@"** Password Hash - %@", fieldString);
                // Save PIN hash to the keychain (NEVER store the direct PIN)
                if ([KeychainWrapper createKeychainValue:fieldString forIdentifier:PIN_SAVED]) {
                    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:PIN_SAVED];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSLog(@"** Key saved successfully to Keychain!!");
                }                
            }
            break;
        default:
            break;
    }
}
There’s a lot to take in here, so let’s step through it together.
  1. First we use our enum again to determine which UITextField we are talking about.
  2. Get the “hash” of our password. A “hash” is simply a fixed-length number generated from another number or string (in our case, the user’s password). We’ll discuss more about why we’re using hashes in a second.
  3. Here we invoke a method called “compareKechainValeuForMatchingPIN:” from a class called KeychainWrapper. We should implement this so that you can see what it does. :] Right now, what you need to know is that it returns a BOOL of whether the value that the user entered matches what we have saved. If it does, then pinValidated is YES, else NO.
  4. We do something similar to step #3, but this time we are generating the hash ourselves and saving that to the NSUserDefaults for our future use.
After reading the above code block, you might think to yourself, “why bother with all of this hash business, and not just use the password directly?”
Storing a user’s password directly is always a bad idea. If you do so, it gives a malicious user or attacker the potential capability of retrieving the user’s raw password, which could lead to all sorts of problems for your users.
Very Important: If you learn nothing else from this tutorial, learn this: NEVER, EVER, EVER, THEN ANOTHER EVER, store the password directly. ALWAYS use some other means of hiding the user’s password, such as a hash – it still uniquely identifies what the user entered, but is not the plain value in clear text.
The same can go for the username, but it is more generally accepted that this can be less restrictive. You also want to apply this to sensitive data like credit card numbers, Social Security numbers, dates of birth – really anything that your user may not want easily exposed.
OK, so now that you know how the overall plan works, let’s implement the security code in the KeychainWrapper class so that we can see this thing in action!
Create a new file with the iOS\Cocoa Touch\Objective-C class template, enter KeychainWrapper for the Class, and make it a subclass of NSObject. Open up KeychainWrapper.h and replace it with the following:
#import <Foundation/Foundation.h>
#import <Security/Security.h>
#import <CommonCrypto/CommonHMAC.h>
 
@interface KeychainWrapper : NSObject
 
// Generic exposed method to search the keychain for a given value. Limit one result per search.
+ (NSData *)searchKeychainCopyMatchingIdentifier:(NSString *)identifier;
 
// Calls searchKeychainCopyMatchingIdentifier: and converts to a string value.
+ (NSString *)keychainStringFromMatchingIdentifier:(NSString *)identifier;
 
// Simple method to compare a passed in hash value with what is stored in the keychain.
// Optionally, we could adjust this method to take in the keychain key to look up the value.
+ (BOOL)compareKeychainValueForMatchingPIN:(NSUInteger)pinHash;
 
// Default initializer to store a value in the keychain.  
// Associated properties are handled for you - setting Data Protection Access, Company Identifer (to uniquely identify string, etc).
+ (BOOL)createKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier;
 
// Updates a value in the keychain. If you try to set the value with createKeychainValue: and it already exists,
// this method is called instead to update the value in place.
+ (BOOL)updateKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier;
 
// Delete a value in the keychain.
+ (void)deleteItemFromKeychainWithIdentifier:(NSString *)identifier;
 
// Generates an SHA256 (much more secure than MD5) hash.
+ (NSString *)securedSHA256DigestHashForPIN:(NSUInteger)pinHash;
+ (NSString*)computeSHA256DigestForString:(NSString*)input;
 
@end
This class is going to do two things for us:
  • Handle read/writes to/from the keychain.
  • Manage our encryption generation methods.
Next switch to KeychainWrapper.m and add the implementation. I’m going to give you all the code at once (and there’s a lot of it!) but don’t worry – we’ll go over it in detail afterwards (plus it has a ton of comments):
#import "KeychainWrapper.h"
#import "ChristmasConstants.h"
 
@implementation KeychainWrapper
// *** NOTE *** This class is ARC compliant - any references to CF classes must be paired with a "__bridge" statement to 
// cast between Objective-C and Core Foundation Classes.  WWDC 2011 Video "Introduction to Automatic Reference Counting" explains this.
// *** END NOTE ***
+ (NSMutableDictionary *)setupSearchDirectoryForIdentifier:(NSString *)identifier {
 
    // Setup dictionary to access keychain.
    NSMutableDictionary *searchDictionary = [[NSMutableDictionary alloc] init];  
    // Specify we are using a password (rather than a certificate, internet password, etc).
    [searchDictionary setObject:(__bridge id)kSecClassGenericPassword forKey:(__bridge id)kSecClass];
    // Uniquely identify this keychain accessor.
    [searchDictionary setObject:APP_NAME forKey:(__bridge id)kSecAttrService];
 
    // Uniquely identify the account who will be accessing the keychain.
    NSData *encodedIdentifier = [identifier dataUsingEncoding:NSUTF8StringEncoding];
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrGeneric];
    [searchDictionary setObject:encodedIdentifier forKey:(__bridge id)kSecAttrAccount];
 
    return searchDictionary; 
}
 
+ (NSData *)searchKeychainCopyMatchingIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    // Limit search results to one.
    [searchDictionary setObject:(__bridge id)kSecMatchLimitOne forKey:(__bridge id)kSecMatchLimit];
 
    // Specify we want NSData/CFData returned.
    [searchDictionary setObject:(__bridge id)kCFBooleanTrue forKey:(__bridge id)kSecReturnData];
 
    // Search.
    NSData *result = nil;   
    CFTypeRef foundDict = NULL;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary, &amp;foundDict);
 
    if (status == noErr) {
        result = (__bridge_transfer NSData *)foundDict;
    } else {
        result = nil;
    }
 
    return result;
}
 
+ (NSString *)keychainStringFromMatchingIdentifier:(NSString *)identifier 
{
   NSData *valueData = [self searchKeychainCopyMatchingIdentifier:identifier];
    if (valueData) {
        NSString *value = [[NSString alloc] initWithData:valueData
                                                   encoding:NSUTF8StringEncoding];
        return value;
    } else {
        return nil;
    }
}
 
+ (BOOL)createKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *dictionary = [self setupSearchDirectoryForIdentifier:identifier];
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    [dictionary setObject:valueData forKey:(__bridge id)kSecValueData];
 
    // Protect the keychain entry so it's only valid when the device is unlocked.
    [dictionary setObject:(__bridge id)kSecAttrAccessibleWhenUnlocked forKey:(__bridge id)kSecAttrAccessible];
 
    // Add.
    OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
 
    // If the addition was successful, return. Otherwise, attempt to update existing key or quit (return NO).
    if (status == errSecSuccess) {
        return YES;
    } else if (status == errSecDuplicateItem){
        return [self updateKeychainValue:value forIdentifier:identifier];
    } else {
        return NO;
    }
}
 
+ (BOOL)updateKeychainValue:(NSString *)value forIdentifier:(NSString *)identifier 
{
 
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    NSMutableDictionary *updateDictionary = [[NSMutableDictionary alloc] init];
    NSData *valueData = [value dataUsingEncoding:NSUTF8StringEncoding];
    [updateDictionary setObject:valueData forKey:(__bridge id)kSecValueData];
 
    // Update.
    OSStatus status = SecItemUpdate((__bridge CFDictionaryRef)searchDictionary,
                                    (__bridge CFDictionaryRef)updateDictionary);
 
    if (status == errSecSuccess) {
        return YES;
    } else {
        return NO;
    }
}
 
+ (void)deleteItemFromKeychainWithIdentifier:(NSString *)identifier 
{
    NSMutableDictionary *searchDictionary = [self setupSearchDirectoryForIdentifier:identifier];
    CFDictionaryRef dictionary = (__bridge CFDictionaryRef)searchDictionary;
 
    //Delete.
    SecItemDelete(dictionary);
}
 
 
+ (BOOL)compareKeychainValueForMatchingPIN:(NSUInteger)pinHash 
{
 
    if ([[self keychainStringFromMatchingIdentifier:PIN_SAVED] isEqualToString:[self securedSHA256DigestHashForPIN:pinHash]]) {
        return YES;
    } else {
        return NO;
    }    
}
 
// This is where most of the magic happens (the rest of it happens in computeSHA256DigestForString: method below).
// Here we are passing in the hash of the PIN that the user entered so that we can avoid manually handling the PIN itself.
// Then we are extracting the username that the user supplied during setup, so that we can add another unique element to the hash.
// From there, we mash the user name, the passed-in PIN hash, and the secret key (from ChristmasConstants.h) together to create 
// one long, unique string.
// Then we send that entire hash mashup into the SHA256 method below to create a "Digital Digest," which is considered
// a one-way encryption algorithm. "One-way" means that it can never be reverse-engineered, only brute-force attacked.
// The algorthim we are using is Hash = SHA256(Name + Salt + (Hash(PIN))). This is called "Digest Authentication."
+ (NSString *)securedSHA256DigestHashForPIN:(NSUInteger)pinHash 
{
    // 1
    NSString *name = [[NSUserDefaults standardUserDefaults] stringForKey:USERNAME];
    name = [name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    // 2
    NSString *computedHashString = [NSString stringWithFormat:@"%@%i%@", name, pinHash, SALT_HASH];
    // 3
    NSString *finalHash = [self computeSHA256DigestForString:computedHashString];
    NSLog(@"** Computed hash: %@ for SHA256 Digest: %@", computedHashString, finalHash);
    return finalHash;
}
 
// This is where the rest of the magic happens.
// Here we are taking in our string hash, placing that inside of a C Char Array, then parsing it through the SHA256 encryption method.
+ (NSString*)computeSHA256DigestForString:(NSString*)input 
{
 
    const char *cstr = [input cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:input.length];
    uint8_t digest[CC_SHA256_DIGEST_LENGTH];
 
    // This is an iOS5-specific method.
    // It takes in the data, how much data, and then output format, which in this case is an int array.
    CC_SHA256(data.bytes, data.length, digest);
 
    // Setup our Objective-C output.
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA256_DIGEST_LENGTH * 2];
 
    // Parse through the CC_SHA256 results (stored inside of digest[]).
    for(int i = 0; i &lt; CC_SHA256_DIGEST_LENGTH; i++) {
        [output appendFormat:@&quot;%02x&quot;, digest[i]];
    }
 
    return output;
}
 
@end
By the time you get to this line of text, you may be shaking or cross-eyed, or feeling uneasy about your future as a security-conscious developer!
It’s actually not that bad. Sure, it looks intimidating, but we’ll get through it in due time. For right now, let’s concentrate on the securedSHA256DigestHashForPIN method (second to last method), which will actually create the value we are going to store in the keychain.
  1. First we get the name the user has entered. This is going to be paired with other values to uniquely create our key and add some extra security to it. Then we Percent Escape the name to avoid any attempted attacks with special characters, etc. The iOS Keychain is UTF8 compliant (only), so we baseline everything to that.
  2. Next, we piece together the user’s name, the hash of the value they entered for their password, and the SALT_HASH string from our ChristmasConstants class. A “salt hash” is just an additional hash (remember, a hash is a fixed-length number based on a number or string) that can be used to augment and enhance the security of the password. The reason that you want to add this is to prevent what’s called a “dictionary attack,” where someone has a whole list of pre-defined passwords and goes about trying every one of them against your password field. If an attacker doesn’t know your salt hash, then they can never generate your password (provided your salt hash is long enough). To add more security, it would be better if it was generated randomly each time, but that’s another day’s tutorial!
  3. Once we have our strong hash built, we pass it over to our computeSHA256DigestForString: method so that we can harden our password even more before storing it.
Now take a look at the computeSHA256DigestForString: method. It takes in a string (like the one from our securedSHA256 method) and puts it inside of a C-Style Character Array. Then it turns around and makes an NSData object of the same size in preparation of the data coming back. The digest array will actually hold our data.
Then we use a convenient CC_SHA256 method (CC being CommonCrypto, Apple’s kind-of-but-not-too-friendly cryptography framework), in which we pass in the data to be encrypted, its length, and where we want the encrypted bytes to be stored.
Once that is done, we work backwards, extract the data out of the digest array, and build a string out of it. And that is what we return.
Just a dozen lines of code (or so) is all it takes to get a pretty strongly-defended password!
One last step – go to the top of ChristmasRootViewController.m and import the KeychainWrapper class:
#import "KeychainWrapper.h"
Let’s build this bad boy one more time to see our security abilities in action!
CKStart –> CKStart2 –> CKTable1
You should be able to run it and create a username and password, and run it a second time and use the same username and password to log in. And best of all, it’s done in a secure manner!

Where to Go From Here?

Here is an example project with all of the code from the tutorial series so far.
That wraps up Part One of this tutorial. To recap, we built out 99% of our UI and workflow via Storyboards, and then we worked on prompting the user for a password.
From a security perspective, you now know a bit about how to properly handle sensitive data, as well as how to generate strongly-encrypted data in order to provide maximum protection for your users. Remember, this is what they expect!
Stay tuned for part two of the series, where we wrap up this project with a few more security features and new iOS5 APIs. We’ve got a bit more explaining to do of what’s inside of the KeychainWrapper class, but I think you’ll find it a great tool for your arsenal of reusable code!
If you have any questions or comments on this tutorial or security in general, please join the discussion below!

This is a post by Chris Lowe, an iOS application developer and aspiring game developer living in San Antonio, Texas.

2011年12月20日星期二

Using Storyboards To Make Navigation Based iPhone Apps

Using Storyboards To Make Navigation Based iPhone Apps:


Over the past few weeks I’ve been doing a series on using the new storyboard feature in XCode for iOS apps. The short story here is that we can now compose our iOS apps in a completely new way when we are coding apps in iOS 5. Storyboards are not backward compatible.

Today, I’m going to show you how to using storyboards to create a navigation based app, with and without a table view. If you haven’t already done so, be sure to read my previous two posts on storyboards in iOS:


Step One: Create a New Storyboard Based iOS Application


Make sure to have a storyboard app started out (covered in the last post on storyboards). Your app will look something like this:


Step Two: Delete Default Scene


We need the navigation controller to be the first scene in our storyboard, so we’ll need to remove the scene that XCode place here for us. Select the scene right in Interface Builder and hit the delete button. You will be left with an empty storyboard.

Step Three: Add A Navigation Controller


Use the object library to drag a navigation controller unto the storyboard. XCode will insert the navigation controller and make it the first scene on the storyboard for you automatically. You will also get the root view controller automatically setup and connected with a seque already connected.

Step Four: Add A Button To The First Scene


Select the scene with the title Root View Controller. Use the object library to drag a button onto the root view controller. Set the button title to Red. It should look something like this:

Step Five: Connect A New Scene To The Button


Now we want to move to a new scene when users touch the Red button. Drag a new view controller from the object library into the storyboard and change the view controller’s background color to red.

Then control-click the button and drag the blue line to the view controller. Choose Push for the seque type. Your storyboard will look something like this:



That’s all there is to it when setting up navigation. Now, I’m going to be clever and add more than one scene to my navigation project. Here is what my storyboard looks like:



This app will push new color scenes to the navigation controller based on what button the user presses. All with no coding at all yet.

Step Six: Pushing Model Content Across Scenes


Usually, when you are working with apps that support navigation you are following the Model-View-Controller (MVC) design pattern. This means that one view controller will need to pass a reference to the part of the model that will be presented in the next view controller. So, here our root view controller might need to pass something to the detail view controllers that we have set up here.

Before, this was done as part of the IBAction associated with a user control or in the table view delegate method didSelectRow:atIndexPath: . But, now we don’t have any code associated with these transitions. Luckily, we can get references to the storyboard components from within our view controllers.

So, all we need to do to pass on model references during these storyboard transitions is to override one of these two key UIViewController methods:

- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender;

To use these method you must make sure that your view controller has a custom code class associated with it. For our example, to set the custom class for our root view controller we can simply use the ViewController that was originally created for us by XCode.

But, we’ll have to set the custom class identity of the view controller on the storyboard to ViewController using Interface Builder.

So, click on the root view controller on the storyboard to select it and then use the Identity Inspector to set the view controller’s custom class to ViewController .



Great, now you can put code into ViewController and it will execute during key events like seque transitions.

In my contrived example, I am going to simply change the view controller’s title property to the text title on the button that the user pressed just to show you how its done:

#import "ViewController.h"

@implementation ViewController

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ UIButton *button = (UIButton *)sender; UIViewController *vc = [segue destinationViewController]; vc.title = button.titleLabel.text; }

@end

Now, when you go from the root view controller to a detail view the title property (in the navigation bar) will change as well. Again, this where you would do something meaningful with your model content.

That’s it for now – keep your eye out for some more storyboard related posts coming out in the near future. Let me know what you think about storyboards in the comments below!

iOS 5 : UIImage and resizableImageWithCapInsets

iOS 5 : UIImage and resizableImageWithCapInsets:
I recently began writing a short example to learn more about the iOS 5 Appearance API and customizing UINavigationBar objects. The goal was to add a custom background, title and text to the navbar. Once I had this working, to keep a consist look across my application, I began tweaking the buttons on the navbar using the same Appearance API.

As I got further into the customization of the buttons, I ran into a method within UIImage that was introduced in iOS 5, resizableImageWithCapInsets. I found myself getting side-tracked from the original idea of navbar look and feel, to understanding how cap insets work. This post delves into what I learned.



Cap Insets with UIButton

As the documentation describes, you use resizableImageWithCapInsets to add cap insets to an image, when the image is resized or scaled, cap areas are not affected. The best way to understand this is through an example.

Let’s assume I want all the buttons on my UI to have a similar look, a gradient with a white border. Below is the image used for the examples in this post (the button is shown on a gray backdrop so you can see the white border):



Depending on the context of where the button appears, its size may vary. The code to create a button with the image and the corresponding output follow:


UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(80, 130, 160, 44)]; 
[button setTitle:@"Test Button" forState:UIControlStateNormal];

// Image with without cap insets
UIImage *buttonImage = [UIImage imageNamed:@"blueButton"];

[button addTarget:self action:@selector(buttonPressed:) forControlEvents: UIControlEventTouchUpInside];       
[button setBackgroundImage:buttonImage forState:UIControlStateNormal];
[[self view] addSubview:button];




As you can see, the button is stretched in all directions. Let’s change the code to include cap insets, however, before we do that, let’s look at the signature of the cap insets method:

- (UIImage *)resizableImageWithCapInsets:(UIEdgeInsets)capInsets

Looking on step further, UIEdgeInserts is defined as:


typedef struct {
CGFloat top, left, bottom, right;
} UIEdgeInsets;


UIEdgeInsets is structure that specifies float values for each cap inset: top, left, bottom and right areas of an image. To apply this to the image for the button, here is all we need to do:


// Image with cap insets
UIImage *buttonImage = [[UIImage imageNamed:@"blueButton"] 
resizableImageWithCapInsets:UIEdgeInsetsMake(0, 16, 0, 16)];


This requests that the left and right 16 pixels of the original image are not scaled or resized when stretching the image to accomodate the button size frame defined above. The end results is as shown below:



Cap Insets with UIBarButtonItem

We can use the same image for a button on a navbar (I’ll show the specifics in the next post on customizing the navbar). Without specifying the cap insets, the button looks as follows:



The code below specifies an image where 12 pixels on the top, left, bottom and right be preserved when stretching/resizing the button:


UIImage *backButton = [[UIImage imageNamed:@"blueButton"] 
resizableImageWithCapInsets:UIEdgeInsetsMake(12, 12, 12, 12)];


The output nows looks as follows:


2011年12月19日星期一

AVPlayer – looping video without “hiccup”/delays

AVPlayer – looping video without “hiccup”/delays:
I tried create loop by AVQueuePlayer, this method has delays between end and start play.

for looping AVQueuePlayer i use this code:

1
2
3
4
5
6
[[NSNotificationCenter defaultCenter] addObserver:self

selector:@selector(playerItemDidReachEnd:)

name:AVPlayerItemDidPlayToEndTimeNotification

object:self.mPlayerItem];



[self player].actionAtItemEnd = AVPlayerActionAtItemEndNone;

and playerItemDidReachEnd

1
2
3
4
5
- (void)playerItemDidReachEnd:(NSNotification *)notification

{

AVPlayerItem *p = [notification object];

[p seekToTime:kCMTimeZero];

}

Another solution without hiccups/delays based on AVMutableComposition!



Easily solution, I use one AVURLAsset for inserting to composition. No memory leaks and warnings, because used just one object.

Solution:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- (AVAsset*) makeAssetComposition {



int numOfCopies = 25;



AVMutableComposition *composition = [[[AVMutableComposition alloc] init] autorelease];

AVURLAsset* sourceAsset = [AVURLAsset URLAssetWithURL:mURL options:nil];



// calculate time

CMTimeRange editRange = CMTimeRangeMake(CMTimeMake(0, 600), CMTimeMake(sourceAsset.duration.value, sourceAsset.duration.timescale));



NSError *editError;



// and add into your composition

BOOL result = [composition insertTimeRange:editRange ofAsset:sourceAsset atTime:composition.duration error:&editError];



if (result) {

for (int i = 0; i < numOfCopies; i++) {

[composition insertTimeRange:editRange ofAsset:sourceAsset atTime:composition.duration error:&editError];

}

}



return composition;

}

Play composition:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
AVAsset *composition = [self makeAssetComposition];



// create an AVPlayer with your composition

AVPlayer* mp = [AVPlayer playerWithPlayerItem:[AVPlayerItem playerItemWithAsset:composition]];



// Add the player to your UserInterface

// Create a PlayerLayer:

AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:mp];



// integrate it to your view. Here you can customize your player (Fullscreen, or a small preview)

[[self window].layer insertSublayer:playerLayer atIndex:0];

playerLayer.frame = [self window].layer.bounds;

playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;

//And finally play your video:



[mp play];

Any questions to comments please.

2011年12月18日星期日

Command Line Tools Tutorial (1)

Command Line Tools Tutorial (1):
Honestly I was very much excited when I found that I can use my current knowledge of Objective-C and Foundation classes like NSString to also build nifty little tools. Previously I had to resort to bash script to perform one-off operations on files that where too tedious to do manually. But knowing what I am going to show you in this article will enable you to also write these littler helpers.

I believe that beginners should rather start with writing a couple of command line tools before diving into building user interface driven apps. Commend line tools are linear and thus their function is easier to grasp. They are more akin to “functional programming” then “object oriented programming” if you will.

I am going to show you what goes into building a simple command line tool and you be the judge whether you agree with my assessment.

Readability

First we need a purpose for our tool. It just so happens that I have a great idea!

Purpose: Join Several Files in a Structure


Somebody handed me a set of all the Localizable.strings files from Apple’s built-in apps. Those are divided by app and there you have one lproj sub-folder per language. I want to join all of these together in a big file so that I want to look up one translation I get all languages at the same time.



The strings files themselves are binary property lists, basically a big NSDictionary each. That’s the same format that they get converted to if you build your app. Xcode takes each text strings file, omits the comment and packs them into the bplist format for faster loading.

Before you set out to coding anything it is a good idea to reflect on which steps we think we require to achieve our goal:


  1. Produce a command line utility that can be called from the terminal and passed one directory as parameters.
  2. Iterate through the directories and get the contained files
  3. Open each file ending in .strings as dictionary
  4. Assemble in memory the tokens contained in each dictionary in a way that will facilitate generating the output we require

Ok, let’s get to it.

Step 1: Command Line Tool with Parameters


We create a new project with the “Command Line Tool” from the Mac OS X/Application category. Under “Type” we see a couple of different templates. We want to use the one that says “Foundation” because this gives us all the Objective-C classes we know and love, like NSArray, NSString etc. Let’s also make it an ARC project so we don’t have to worry about memory management. I called my tool stringsextract.

As with all C-based applications the starting point for the program is in the main function which you can find in main.m.


int main (int argc, const char * argv[])
{
@autoreleasepool {
// insert code here...
NSLog(@"Hello, World!");
}
return 0;
}


If it weren’t for the autorelease pool this would look like a very normal C-function. In objc methods generally are either class (+) or instance methods (-). In c functions are standing alone.

This function main has an int as return value. If the program runs without error you want it to return 0, otherwise you want it to return something else, like 1.

It has two parameters argc and argv. The first (argument count) is the number of parameters contained in the second (argument values). Int is just a number, but the second looks a bit more completed to the untrained eye. It is an array of char pointers. Since in c arrays are same as pointers you sometimes see this also written as char **argv, because in essence it is a pointer to a pointer to a char.

Arrays in C are not secured against being overrun which is why we need the argc. Otherwise we would have no way of knowing how many entries this array has. C-style arrays are just some memory where the elements are in sequential order. To access the nth item, you use array[n-1] and the compiler will convert that into the correct memory address. (Note: in c indexes begin with 0)

Another thing to know about argc/argv is that there is always at least one parameter at index 0: the name and path of the executable. So even if you call this program without any parameters on the command line argc will be 1 and there will be a value in argv[0].

The next tricky thing besides having to deal with a c-style array is that we also have to know c-style strings to make sense of the argument values. I told you above that an array is just a bunch of items. C-strings are just a bunch of characters where the last one is a binary zero, aka ‘\0′, to delimit the string. So whenever you see char * this could either be a pointer to one character or it could be a pointer to the first character of a string.

Since we want to use Foundation constructs for our program we want to convert all c-stuff to the more intelligent variants like NSString, by means of stringWithUTF8String.

As a first experiment let’s output all the arguments. We do a normal for loop beginning with 0, convert each argument to an NSString and log it.


for (int i=0; i<argc; i++)
{
NSString *str = [NSString stringWithUTF8String:argv[i]];
NSLog(@"argv[%d] = '%@'", i, str);
}


If you hit Run now you will see the following output on the console:


2011-12-11 09:21:58.636 stringsextract[18003:707] argv[0] = '/Users/oliver/Library/Developer/Xcode/DerivedData/stringsextract-dlkdghopgfoghoanjhmahhrlotsp/Build/Products/Debug/stringsextract'


So really what I told you is true, the parameter at index 0 has the path of our binary.

How can we test our program while we are still working on it? Of course you could open a terminal and run it by hand:


iair:~ oliver$ cd /Users/oliver/Library/Developer/Xcode/DerivedData/stringsextract-dlkdghopgfoghoanjhmahhrlotsp/Build/Products/Debug/
iair:Debug oliver$ ./stringsextract bla
2011-12-11 09:25:03.357 stringsextract[18017:707] argv[0] = './stringsextract'
2011-12-11 09:25:03.363 stringsextract[18017:707] argv[1] = 'bla'


You see how I changed into the Debug output directory and executed the program there passing one extra parameter. The dot slash is necessary to tell the shell that it should take the stringsextract binary right there in the current directory. Otherwise it would go off searching the set up system paths. You also see that argv[0] does not actually contain the absolute path, but always how it was called.

Now this works, but it might be a bit tedious to work with while we are still testing and debugging our tool. Fortunately Xcode allows us to specify command line arguments in the schema. If one argument contains whitespace you need to put it in quotes.



If we hit Run like this then we can also debug and step through our code as if we had passed this parameter on the command line ourselves.

As a final step in this chapter let us add a usage text which is to be output if somebody calls this program of ours without the required one parameter.


// one parameter is required
if (argc!=2)
{
// output usage
printf("Usage: stringsextract <dir>\n");

// leave with code 1
exit(1);
}


Note the use of the c-function printf which unlike NSLog just outputs the stuff we want and no extra stuff.

Now we’re set to move to Step 2.

Step 2: Getting the Files


Foundation gives us some awesome utilities when working with the file system, most notably NSFileManager which groups together most of them. We have our parameter specifying an absolute path. So next we need to list the .app bundles contained in there.

Usually you would use [NSFileManager defaultManager] to get a file manager instance. Only if you need to set a call-back delegate you would go about alloc/init’ing it.

So following our check for the existence of at least one parameter we add:


// convert path to NSString
NSString *path = [NSString stringWithUTF8String:argv[1]];

// get file manager
NSFileManager *fileManager = [NSFileManager defaultManager];

// get directory contents
NSError *error;
NSArray *contents = [fileManager contentsOfDirectoryAtPath:path
error:&error];

// handle error
if (!contents)
{
printf("%s\n",[[error localizedDescription] UTF8String]);
exit(1);
}

NSLog(@"%@", contents);


This converts the parameter to an NSString, sets up a file manager and then gets the contents of the specified path. If this is successful then there is a non-nil value in contents. If not then error will point to a new NSError instance which gives us a nice localized description to tell the user. Again we use printf because we want the direct output. UTF8String is the method to get from an objective-C NSString to back to a regular C-string which is required by the %s print format.

The NSLog at the bottom is just temporary so that we can see if we indeed got a result. And so we did.


2011-12-11 10:08:47.023 stringsextract[18231:707] (
".DS_Store",
"AppStore.app",
"Calculator.app",
"Camera.app",
"Compass.app",
"Contacts~iphone.app",
"Game Center~iphone.app",
"Maps~iphone.app",
"MobileCal.app",
"MobileMail.app",
"MobileNotes.app",
"MobilePhone.app",
"MobileSafari.app",
"MobileSlideShow.app",
"MobileSMS.app",
"MobileStore.app",
"Music~iphone.app",
"Nike.app",
"Preferences.app",
"Reminders.app",
"Setup.app",
"Stocks.app",
"Videos.app",
"Weather.app",
"YouTube.app"
)
Program ended with exit code: 0


We also see that there is one entry that we want to ignore later on, the “.DS_Store”. So let’s filter out everything that does not end in .app as I showed in a previous post.

Now we need to iterate through the array of app paths and get the contents of these, filtering for lproj. Since the contents are without the full path we need to concatenate the individual names with the path.


// filter
NSArray *filter = [NSArray arrayWithObject:@"app"];

// execute filter in place
contents = [contents pathsMatchingExtensions:filter];

// iterate through .app
for (NSString *oneApp in contents)
{
// make full path
NSString *appPath = [path stringByAppendingPathComponent:oneApp];

// get contents, ignore error
NSArray *appContents = [fileManager contentsOfDirectoryAtPath:appPath
error:NULL];

NSLog(@"app: %@, %@", oneApp, appContents);

}


Again we have a bunch of files that we one and one that we don’t, in this case I have have a _CodeResources. Granted I could have removed these by hand but we’re writing this program here to be smart and save us manual labor. So we code around that just the same.

Rinse and repeat. We end up with three loops, one for the apps, one for the lprojs and one for the strings.


int main (int argc, const char * argv[])
{
@autoreleasepool
{
// one parameter is required
if (argc!=2)
{
// output usage
printf("Usage: stringsextract <dir>\n");

// leave with code 1
exit(1);
}

// convert path to NSString
NSString *path = [NSString stringWithUTF8String:argv[1]];

// get file manager
NSFileManager *fileManager = [NSFileManager defaultManager];

// get directory contents
NSError *error;
NSArray *contents = [fileManager contentsOfDirectoryAtPath:path
error:&error];

// handle error
if (!contents)
{
printf("%s\n",[[error localizedDescription] UTF8String]);
exit(1);
}

// filter
NSArray *filter = [NSArray arrayWithObject:@"app"];

// execute filter in place
contents = [contents pathsMatchingExtensions:filter];

// iterate through .app
for (NSString *oneApp in contents)
{
// make full path
NSString *appPath = [path stringByAppendingPathComponent:oneApp];

// get contents, ignore error
NSArray *appContents = [fileManager contentsOfDirectoryAtPath:appPath
error:NULL];

// new filter
filter = [NSArray arrayWithObject:@"lproj"];

// execute filter in place
appContents = [appContents pathsMatchingExtensions:filter];

// iterate through .lproj = one language
for (NSString *oneLang in appContents)
{
// make full path
NSString *langPath = [appPath stringByAppendingPathComponent:oneLang];

// get contents, ignore error
NSArray *langContents = [fileManager contentsOfDirectoryAtPath:langPath
error:NULL];

// new filter
filter = [NSArray arrayWithObject:@"strings"];

// execute filter in place
langContents = [langContents pathsMatchingExtensions:filter];


for (NSString *oneStrings in langContents)
{
// make full path
NSString *stringsPath = [langPath stringByAppendingPathComponent:oneStrings];

// do work here
NSLog(@"%@", stringsPath);
}
}
}
}
return 0;
}


If this code makes your stomach churn then this is because this more and more turns into spaghetti code. This can still be fine for a one-off tool, but should be avoided if you plan to hand out this tool for others to use.

For one thing I would add a category to NSFileManager that does the listing, filtering and full-path-assembling in one step. Or possibly even go one further to have the working code in a block and have this category iterate over the strings files.

This we will be exploring in the next installment of this two part tutorial.

Xcode 4 : Show Invisibles to Find Tabs and Spaces

Xcode 4 : Show Invisibles to Find Tabs and Spaces:
Every now and again I experience some rather odd code formatting behavior when I copy/paste from Xcode into another editor, an email or this blog. I’m never quite sure just where the weirdness originates, most likely an errant tab that was inadvertently introduced somewhere on the way.

For example, this screenshot from Xcode looks rather innocuous:





However, if I copy and paste the same code into the editor that I am using to write this post, the formatting looks as follows:


- (void)applicationDidFinishLaunching:(UIApplication *)application
{  
// Create and initialize the window
window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
window.backgroundColor = [UIColor blackColor];

// Create test view controller
vc = [[MainViewController alloc] init];

[window makeKeyAndVisible];
[window addSubview:[vc view]];

}


Within Xcode 4, in the Editor drop-down menu there is an option to Show Invisibles. Once enabled, you can see where tabs and spaces are embedded within the code.



Space characters are shown as a diamond shape – the red boxes (I added) highlight where tab characters are embedded in the source code, resulting in the funky formatting shown above. Replace the tabs with spaces and all is well.