Introduction
In this article I will create a Single View application. Here in the first view I use an image view, one label and one button from outlet. In this app I will implement a Security alert view. To do that, the very first thing to do is to add a Security framework. In the second view I use a Customize table view and add it on the image or label, at last in the third view I use an image view and text view.
To understand it we use the following.
Step 1
Here first we add a Security framework which is required to implement the Secure alert view.
To import this framework we use the following.
Step 2
Click on the project and select Build Phase.
Step 3
Click on the "+" icon to add the framework.

Step 4
Now select the Security framework and click on the add button.
Step 5
Now we write the code for each class.
AppDelegate.h
//
// AppDelegate.h
// Happy Christmas
//
// Created by Sachin Bhardwaj on 21/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import <UIKit/UIKit.h>
@class ViewController;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) ViewController *viewController;
@property (strong,nonatomic) UINavigationController *nav;
@end
AppDelegate.m
//
// AppDelegate.m
// Happy Christmas
//
// Created by Sachin Bhardwaj on 21/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import "AppDelegate.h"
#import "ViewController.h"
@implementation AppDelegate
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
// Override point for customization after application launch.
self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
self.nav=[[UINavigationController alloc]initWithRootViewController:self.viewController];
self.window.rootViewController = self.nav;
[self.window makeKeyAndVisible];
return YES;
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
@end
ViewController.h
//
// ViewController.h
// Happy Christmas
//
// Created by Sachin Bhardwaj on 21/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UITextFieldDelegate>
{
IBOutlet UIButton *btn;
IBOutlet UILabel *lbl;
IBOutlet UIImage *img;
}
@property(nonatomic,strong)IBOutlet UIButton *btn;
@property(nonatomic,strong)IBOutlet UILabel *lbl;
@property(nonatomic,strong)IBOutlet UIImage *img;
@property (nonatomic) BOOL pinValidated;
-(IBAction)click;
@end
ViewController.m
//
// ViewController.m
// Happy Christmas
//
// Created by Sachin Bhardwaj on 21/12/12.
// Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.
//
#import "ViewController.h"
#import "KeychainWrapper.h"
#import "ChristmasConstants.h"
#import "GiftsViewController.h"
@interface ViewController ()
@end
@implementation ViewController
@synthesize pinValidated;
@synthesize lbl,btn,img;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
-(IBAction)click
{
NSLog(@"click");
GiftsViewController *bk = [[GiftsViewController alloc ]init];
[self.navigationController pushViewController:bk animated:YES];
}
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
// 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;
}
}
- (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];
}
}
//- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex
//{
// if (alertView.tag == kAlertTypePIN) {
// if (buttonIndex == 1 && self.pinValidated) { // User selected "Done"
// [self performSegueWithIdentifier:@"GiftsViewController" 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:@"GiftsViewController" sender:self];
// } else { // User selected "Cancel"
// [self presentAlertViewForPassword];
// }
// }
//}
#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;
}
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.pinValidated = NO;
self.title=@"Happy Christmas";
self.navigationController.navigationBar.barStyle = UIBarStyleBlackOpaque;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self presentAlertViewForPassword];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
@end
KeychainWrapper.h
#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
KeychainWrapper.m










Comments
Join the conversation! Your thoughts help the community grow.