iOS (iPhone, iPad) Tutorial
iOS is a mobile operating system developed and distributed by Apple Inc. Originally released in 2007 for the iPhone, iPod Touch, and Apple TV. iOS is derived from OS X, with which it shares the Darwin foundation. iOS is Apple's mobile version of the OS X operating system used on Apple computers.
iOS - Getting Started
General Overview
iOS which was previously called iPhone OS is a mobile operating system developed by Apple Inc. Its first release was in 2007 which included iPhone and iPod Touch. iPad (1st Generation) was released in the April 2010 and in iPad mini was released in November 2012
The iOS devices get evolved quite frequently and from the experience we find that at least one version of iPhone and iPad is launched every year. Now we have iphone5 launched which has its predecessors starting from iPhone, iPhone 3gs, iPhone 4, iPhone 4s. Similarly iPad has evolved from iPad (1st Generation) to iPad(4th Generation) and an additional iPad mini version.
The iOS SDK has evolved from 1.0 to 6.0. iOS 6.0, the latest SDK is the only officially supported version in Xcode 4.5 and higher. We have rich apple documentation and we can find which methods and libraries can be used based on our deployment target. In the current version of Xcode, we’ll be able to choose between deployment targets of iOS 4.3, 5.0 and 6.0..
The power of iOS can be felt with some of the following features provided part of the device.
- Maps
- Siri
- Facebook and Twitter
- Multi-Touch
- Accelerometer
- GPS
- High end processor
- Camera
- Safari
- Powerful APIs
- Game center
- In-App Purchase
- Reminders
- Wide Range of gestures
The number of users using iPhone/iPad has increased a great deal. This creates the opportunity for developers to make money by creating applications for iPhone and iPad the Apple's App Store.
For some one new to iOS, Apple has designed an application store where the user can buy apps developed for their iOS devices. A developer can create both free and paid apps to App Store. To develop applications and distribute to the store the developer will require to register with iOS developer program which cost $99 a year and a Mac with Mountain Lion or higher for its development with latest Xcode.
Registering as an Apple developer
An apple ID is most necessary if you are having any apple device and being a developer, you definitely need it. It's also free and hence no issues in having one. The benefits of having an apple account are as follows,
- Access to development tools
- Worldwide Developers Conference (WWDC) videos
- Can join iOS developer program teams when invited
To register an apple account for you
1. Click the link (https://developer.apple.com/programs/register/) and select "Create Apple ID"
2. Provide the necessary information which is self explanatory as given in the page.
3. Verify your account with your email verification and account becomes active.
4. Now you will be able to download the developer tools like Xcode which is packaged with iOS simulator and iOS SDK, and other developer resources.
Apple iOS Developer Program
The first question that would arise to a new developer is why I should register for iOS developer program. The answer is quite simple; Apple always focuses on providing quality applications to its user. If there was no registration fee there could be a possibility of junk apps being uploaded and cause problem for app review team of Apple.
The benefits of joining iOS developer program are as follows,
- Run the apps you develop on the real iOS device
- Distribute the apps to app store
- Get access to developer previews
The steps to join iOS developer program are as follows
1. To register click (https://developer.apple.com/programs/ios/)
2. Click enroll now in the page that is displayed
3. Then you can either sign in to your existing apple account (if you have one) or create a new Apple ID.
4. Then you have to select between Individual and Company accounts. Use company account if there will be more than one developer in your team. In individual account you can't add members.
5. Then after entering the personal information (for those who newly registers), you can purchase and activate the program by paying with the help of your credit card (Only accepted mode of payment).
6. Now you will get access to developer resources by selecting the member center option in the page.
7. Here you will be able to do the following,
- Create provisioning profiles
- Manage your team and devices
- Managing application to app store through iTunes Connect
- Get forum and technical support
iOS - Environment Setup
iOS - Xcode Installation
1. Download Xcode latest version from (https://developer.apple.com/downloads/)
2. Double click the Xcode dmg file.
3. You will find a device mounted and opened.
4. Here there will be two items in the window that's displayed namely Xcode application and the Application folder's shortcut.
5. Drag the Xcode to application and it will be copied to your applications.
6. Now Xcode will be available part of other applications from which you can select and run.
You also have another option of downloading Xcode from the Mac App store and then install following the step by step procedure given in the screen.
Interface Builder
Interface builder is the tool that enables easy creation of UI interface. You have a rich set of UI elements that is developed for use. You have just drag and drop into your UI view. We'll learn about adding UI elements, creating outlets and actions for the UI elements in the upcoming pages.
You have objects library in right bottom that consists the entire necessary UI element. The user interface is often referred as xibs which is their file extension. Each of the xibs is linked to a corresponding view controller.
iOS simulator
iOS simulator actually consists of two types of devices namely iPhone and iPad with its different versions. iPhone versions include iPhone (normal), iPhone Retina, iPhone 5 .iPad has iPad and iPad Retina. iPhone simulator is displayed below.
You can simulate location in iOS simulator for playing around with latitude and longitude effects of the app. You can also simulate memory warning and in-call status in the simulator. You can be able to use the simulator for most purposes. But you cannot test the device features like accelerometer. So you might always need an iOS device to test thoroughly on all aspect and scenarios of an application.
iOS - Objective C
Introduction
The language used in iOS development is objective C. It is an object oriented language and hence it would easy for those who have some background in object oriented language programming.
Interface and Implementation
In objective C the file where the declaration of class is done is called the interface file and the file where the class is defined is called the implementation file.
A simple interface file MyClass.h would look like the following.
@interace MyClass:NSObject{ // class variable declared here } // class properties declared here // class methods and instance methods declared here @end
The implementation file MyClass.m would be like follows
@implementation MyClass // class methods defined here @end
Object Creation
Object creation is done as follows
MyClass *objectName = [[MyClass alloc]init] ;
Methods
Method is declared in objective C as follows
-(returnType)methodName:(typeName) variable1 :(typeName)variable2;
An example is shown below
-(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth;
You might be wondering what the andBreadth string for; actually its optional string which helps us read and understands the method easier especially at the time of calling. To call this method in the same class we use the following statement
[self calculateAreaForRectangleWithLength:30 andBreadth:20];
As said above the use of andBreadth helps us understand that breath is 20. Self is used to specify it's a class method.
Class method
Class methods can be accessed directly without creating objects for the class. They don't have any variables and objects associated with it. An example is shown below.
+(void)simpleClassMethod;
It can be accessed by using the class name (let's assume the class name as MyClass) as follows.
[MyClass simpleClassMethod];
Instance methods
Instance methods can be accessed only after creating an object for the class. Memory is allocated to the instance variables. An example instance method is shown below.
-(void)simpleInstanceMethod;
It can be accessed after creating an object for the class as follows
MyClass *objectName = [[MyClass alloc]init] ; [objectName simpleInstanceMethod];
Important data types in Objective C
S.N. | Data Type |
---|---|
1 | NSString It is used for representing a string |
2 | CGfloat It is used for representing a floating point value (normal float is also allowed but it's better to use CGfloat) |
3 | NSInteger It is used for representing integer |
4 | BOOL used for representing Boolean(YES or NO are BOOL types allowed ) |
Printing logs
NSLog - used for printing a statement. It will be printed in device logs and debug console in release and debug modes respectively.
Eg: NSlog(@"");
Control Structures
Most of control structures are same as in C and C++ except for a few additions like for in statement.
Properties
For an external class to access class variables properties are used
Eg: @property(nonatomic , strong) NSString *myString;
Accessing Properties
You can use dot operator to access properties. To access the above property we will do the following.
self.myString = @"Test";
You can also use set method as follows.
[self setMyString:@"Test"];
Categories
Categories are use to add methods to existing classes. By this way we can add method to classes for which we don't have even implementation files where the actual class is defined. A sample category for our class is as follows.
@interace MyClass(customAdditions) - (void)sampleCategoryMethod; @end @implementation MyClass(categoryAdditions) -(void)sampleCategoryMethod{ NSLog(@"Just a test category"); }
Arrays
NSMutableArray and NSArray are the array classes used in objective C. As the name suggests the former is mutable and latter is immutable. An example is shown below.
NSMutableArray *aMutableArray = [[NSMutableArray alloc]init]; [anArray addObject:@"firstobject"]; NSArray *aImmutableArray = [[NSArray alloc] initWithObjects:@"firstObject",nil];
Dictionary
NSMutableDictionary and NSDictionary is the dictionary classes used in objective C. As the name suggests the former is mutable and latter is immutable. An example is shown below.
NSMutableDictionary*aMutableDictionary = [[NSMutableArray alloc]init]; [aMutableDictionary setObject:@"firstobject" forKey:@"aKey"]; NSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects: @"firstObject",nil] forKeys:[ NSArray arrayWithObjects:@"aKey"]];
iOS - First iPhone Application
Creating our First App
Now we are just going to create a simple single view application (a blank app) that just runs on the iOS simulator.
The steps are as follows.
1. Open Xcode and select create a new Xcode project.
2. Then select single view application
3. Then enter product name i.e. the name of the application, organization name and then the company identifier
4. Ensure Use automatic reference counting is selected in order to automatically release the resources allocated once it goes out of scope. Click Next.
5. Select the directory for the project and select create.
6. You will see a screen as follows
In the screen above you will able to select the supported orientations, build and release settings. There is a field deployment target, the device version from which we want to support, lets select 4.3 which is the minimum deployment target allowed now. For now these are not required and let's focus on running the application.
7. Now select iPhone simulator in the drop down near Run button and select run.
8. That's it; you have successfully run your first application. You will get an output as follows
Now let's change the background color, just to have a start with interface builder. Select ViewController.xib. Select background option in the right side, change the color and run.
In the above project, by default the deployment target would have been set to iOS 6.0 and auto layout will be enabled. But to ensure our application to run on devices that run iOS 4.3 onwards, we have already modified the deployment target at the start of creation of this application but we didn't disable auto layout, to disable auto layout we need to deselect the auto layout checkbox in file inspector of each nib i.e the xib files. The various sections of Xcode project IDE are given in the following figure (Courtesy: Apple Xcode 4 User documentation).
File inspector is found in the inspector selector bar as shown above and auto layout can be unchecked there. Auto layout can be used when you want to target only iOS 6 devices. Also you'll be able to use many new features like passbook if you raise the deployment target to iOS 6. For now let's stick to iOS 4.3 as deployment target.
Digging deep into the code of the First iOS application
You will find 5 different files that would have been generated for your application. They are listed as follows.
- AppDelegate.h
- AppDelegate.m
- ViewController.h
- ViewController.m
- ViewController.xib
We use these single line comments (//) to give simple code explanations and important items explained below the code.
AppDelegate.h
// Header File that provides all UI related items. #import <UIKit/UIKit.h> // Forward declaration (Used when class will be defined /imported in future) @class ViewController; // Interface for Appdelegate @interface AppDelegate : UIResponder <UIApplicationDelegate> // Property window @property (strong, nonatomic) UIWindow *window; // Property Viewcontroller @property (strong, nonatomic) ViewController *viewController; //this marks end of interface @end
Important items in code
- AppDelegate inherits from UIResponder that handles iOS events
- Implements the delegate methods of UIApplication delegate which provide key application events like finished launching, about to terminate and so on.
- UIWindow object to manage and co-ordinate the various views on the iOS device screen. It's like the base view over which all other views are loaded. Generally there is only one window for an application.
- UIViewController to handle the screen flow.
AppDelegate.m
// Imports the class Appdelegate's interface import "AppDelegate.h" // Imports the viewcontroller to be loaded #import "ViewController.h" // Class definition starts here @implementation AppDelegate // Following method intimates us the application launched successfully - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.viewController = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil]; self.window.rootViewController = self.viewController; [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
Important items in code
- UIApplication delegates defined here. All the methods defined above are UI application delegates and contains no user defined methods.
- UIWindow object is allocated to hold the application is allocated
- UIViewController is allocated made as window's initial view controller.
- To make window visible makeKeyAndVisible method is called.
ViewController.h
#import// Interface for class ViewController @interface ViewController : UIViewController @end
Important items in code
- The ViewController class inherits the UIViewController which provides the fundamental view management model for the iOS applications.
ViewController.m
#import "ViewController.h" // Category, an extension of ViewController class @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
Important items in code
- Two methods implemented here which are defined in the base class UIViewController
- Do initial setup in viewDidLoad which is called after view loads
- didReceiveMemoryWarning method is called in case of memory warning.
iOS - Actions and Outlets
Introduction
Actions and outlets in iOS are referred to as ibActions and ibOutlets respectively where ib stands for interface builder. These are related to the UI elements and we will explore them after knowing visually how to implement them.
Steps Involved
1. Let's use our First iPhone Application.
2. Select the ViewController.xib file from the files in the navigator section.
3. Now you can select the UI elements from the library pane in right hand side of our window which is shown below.
4. You can drag and drop UI elements to our view in our interface builder.
5. Let add a Label and Round Rect Button to our view.
6. From the Editor selector button in the workspace toolbar found on the top right corner as shown below.
Select Assistant editor button
7. We will see two windows in our editor area in the center, one is ViewController.xib file and other is ViewController.h
8. Now right click on the label and select, hold and drag new referencing outlet as shown below
9. Now drop in the ViewController.h in between the curly braces. There may be no curly brace please in the file, if so add before doing this. You will find a pop up as shown below.
10. Now type the label name for the outlet, here I have given myTitleLabel. Click connect and the ibOutlet will be complete.
11. Similarly to add an action right click the Round rect button, select touch up inside and drag it below the curly braces
12. Drop it and name it setTitleLabel.
13. Now select ViewController.m file, you'll find a method as shown below.
-(IBAction) setTitleLabel:(id)sender{ }
14. Add a statement as shown below inside the above method.
[myTitleLabel setTitleText:@"Hello"];
15. Now let's run the program by selecting the run button. You will see the following output.
16. Now click the button.
17. The label that we created outlet have been changed by the action on the button.
18. So from the above example we can conclude that IBOutlet creates a reference to the UIElement (here for the UILabel) and similarly the IBAction links the UIButton with a method which is called on the event touch up inside.
19. You can play around with actions by selecting different events while creating the action.
iOS - Delegates
Example for delegate
Let's assume an object A calls object B to perform an action, once the action is complete object A should know that B has completed the task and take necessary action. This is achieved with the help of delegates.
The key concepts in the above example are,
- A is delegate object of B
- B will have a reference of A
- A will implement the delegate methods of B.
- B will notify A through the delegate methods.
Steps in creating a delegate
1. First, create a single view application.
2. Then select File -> New -> File...
3. Then select Objective C Class and click Next.
4. Give the name for the class say SampleProtocol with subclass as NSObject as shown below.
5. Then select create.
6. Add a protocol to the SampleProtocol.h file and updated code is as follows.
#import <Foundation/Foundation.h> // Protocol definition starts here @protocol SampleProtocolDelegate <NSObject> @required - (void) processCompleted; @end // Protocol Definition ends here @interface SampleProtocol : NSObject { // Delegate to respond back id <SampleProtocolDelegate> _delegate; } @property (nonatomic,strong) id delegate; -(void)startSampleProcess; // Instance method @end
7. Implement the instance method by updating the SampleProtocol.m file as shown below.
#import "SampleProtocol.h" @implementation SampleProtocol -(void)startSampleProcess{ [NSTimer scheduledTimerWithTimeInterval:3.0 target:self.delegate selector:@selector(processCompleted) userInfo:nil repeats:NO]; } @end
8. Add an UILabel in the ViewController.xib by dragging the label from the object library to UIView as shown below.
9. Create an IBOutlet for the label and name it as myLabel and update the code as follow to adopt SampleProtocolDelegate in ViewController.h
#import <UIKit/UIKit.h> #import "SampleProtocol.h" @interface ViewController : UIViewController<SampleProtocolDelegate> { IBOutlet UILabel *myLabel; } @end
10. Implement the delegate method, create object for SampleProtocol and call the startSampleProcess method. The Updated ViewController.m file is as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; SampleProtocol *sampleProtocol = [[SampleProtocol alloc]init]; sampleProtocol.delegate = self; [myLabel setText:@"Processing..."]; [sampleProtocol startSampleProcess]; // Do any additional setup after loading the view, typically from a nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } #pragma mark - Sample protocol delegate -(void)processCompleted{ [myLabel setText:@"Process Completed"]; } @end
11. We will see an output as follows, initially the label will be processing which gets updated once the delegate method is called by the SampleProtocol object.
iOS - UI Elements
What UI elements are?
UI elements are visual elements that we can see in our abpplications. Some of these elements respond to user interactions such as buttons, text fields and others are informative such as images, labels.
How to add UI elements?
We can add UI elements both in code and with the help of interface builder. Depending on the need we can use either one of them.Our Focus
We'll be focussing more on adding UI elements through code in our applications. Using interface builder is simple and straight forward, we just need to drag and drop UI elements.Our Approach
We will create a simple iOS application and use it for explaining some of the UI elements.
Steps
1. Create a Viewbased application as we did in our First iOS application
2. We will be only updating the ViewController.h and ViewController.m files.
3. Then we add a method to our ViewController.m file specific to creating the UI element.
4. We will call this method in our viewDidLoad method.
5. The important lines of code have been explained in the code with single line comment above those lines.
List of UI elements
UI specific elements and their related functionalies are explained below
S.N. | UI specific elements or funtionality |
---|---|
1 | Text Fields It is an UI element that enables the app to get user input. |
2 | Input types - TextFields We can set the type of input that user can give by using the keyboard property of UITextField |
3 | Buttons It is used for handling user actions. |
4 | Label It is used for displaying static content. |
5 | Toolbar It is used if we want to manipulate something based on our current view. |
6 | Status Bar It displays the key information of device. |
7 | Navigation Bar It contains the navigation buttons of a navigation controller which is a stack of view controllers which can be pushed and popped. |
8 | Tab bar It generally used to switch between various subtasks, views or models within the same view. |
9 | Image View It is used to display a simple image or sequence of images. |
10 | Scroll View It is used to display content that is more than the area of screen. |
11 | Table View It is used for displaying scrollable list of data in multiple rows and sections. |
12 | Split View It is used for displaying a two panes with master pane controlling information on detail pane. |
13 | Text View It is used for diplaying scrollable list of text information that is optionally editable. |
14 | View Transition It explains the various view transitions between views. |
15 | Pickers It is used for displaying for selecting a specific data from a list. |
16 | Switches It is used as disable and enable for actions. |
17 | Sliders It is used to allow users to make adjustments to a value or process throughout a range of allowed values. |
18 | Alerts It is used to give important information to user. |
19 | Icons It is an image representation used for an action or depict something related to the application. |
iOS - Accelerometer
Introduction
Accelerometer is used for detecting the changes in the position of the device in the three directions x, y and z. We can know the current position of the device relative to ground. For testing this example you'll need it run it on device and it doesn't work on simulator.
Steps Involved
1. Create a simple View based application.
2. Add three labels in ViewController.xib and create ibOutlets naming them as xlabel, ylabel and zlabel.
3. Update ViewController.h as follows.
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIAccelerometerDelegate> { IBOutlet UILabel *xlabel; IBOutlet UILabel *ylabel; IBOutlet UILabel *zlabel; } @end
4. Update ViewController.m as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[UIAccelerometer sharedAccelerometer]setDelegate:self]; //Do any additional setup after loading the view,typically from a nib } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate: (UIAcceleration *)acceleration{ [xlabel setText:[NSString stringWithFormat:@"%f",acceleration.x]]; [ylabel setText:[NSString stringWithFormat:@"%f",acceleration.y]]; [zlabel setText:[NSString stringWithFormat:@"%f",acceleration.z]]; } @end
Output
Now when we run the application in iPhone device we'll get the following output.
iOS - Universal Applications
Introduction
Universal application is the application that is designed for both iPhone and iPad in a single binary. This helps in code reuse and helps in making updates faster.
Steps Involved
1. Create a simple View based application.
2. Change the File name ViewController.xib file to ViewController_iPhone.xib as shown below in the file inspector in the right hand side.
3. Select File -> New -> File... then select the subsection "User Interface" and select View. Click Next.
4. Now select the device family as iPad and click next.
5. Save the file as ViewController_iPad.xib and select Create.
6. Add a label in center of screen in both ViewController_iPhone.xib and ViewController_iPad.xib.
7. Now in ViewController_iPad.xib select the identity inspector and set the custom class asViewController.
8. Update the application:DidFinishLaunching:withOptions method in AppDelegate.m as follows
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) { self.viewController = [[ViewController alloc] initWithNibName:@"ViewController_iPhone" bundle:nil]; } else{ self.viewController = [[ViewController alloc] initWithNibName: @"ViewController_iPad" bundle:nil]; } self.window.rootViewController = self.viewController; [self.window makeKeyAndVisible]; return YES; }
9. Update the devices in project summary to Universal as shown below.
Output
Now when we run the application we'll get the following output.
When we run the application in iPad simulator we'll get the following output.
iOS - Camera Management
Introduction
Camera is one of the common features of mobile devices. It is possible for us to take pictures with the camera and use it in our application and it is quite simple too.
Steps Involved
1. Create a simple View based application.
2. Add a button in ViewController.xib and create IBAction for the button.
3. Add an image view and create IBOutlet naming it as imageView.
4. Update ViewController.h as follows.
#import <UIKit/UIKit.h> @interface ViewController : UIViewController<UIImagePickerControllerDelegate> { UIImagePickerController *imagePicker; IBOutlet UIImageView *imageView; } - (IBAction)showCamera:(id)sender; @end
5. Update ViewController.m as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } - (IBAction)showCamera:(id)sender { imagePicker.allowsEditing = YES; if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]) { imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera; } else{ imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; } [self presentModalViewController:imagePicker animated:YES]; } -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{ UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage]; if (image == nil) { image = [info objectForKey:UIImagePickerControllerOriginalImage]; } imageView.image = image; } -(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{ [self dismissModalViewControllerAnimated:YES]; } @end
Output
Now when we run the application and click show camera button we'll get the following output.
Once we take picture we can edit the picture i.e. move and scale as shown below.
iOS - Location Handling
Introduction
In iOS we can easily locate the user's current location provided the user allows the application to access the information with the help of core location framework.
Steps Involved
1. Create a simple View based application.
2. Select your project file, then select targets and then add CoreLocation.framework as shown below.
3. Add two labels in ViewController.xib and create ibOutlets naming the labels as latitudeLabel andlongitudeLabel respectively.
4. Now create a new file by selecting File-> New -> File... -> select Objective C class and click next
5. Name the class as LocationHandler with "sub class of" as NSObject.
6. Select create.
7. Now update the LocationHandler.h as follows
#import <Foundation/Foundation.h> #import <CoreLocation/CoreLocation.h> @protocol LocationHandlerDelegate <NSObject> @required -(void) didUpdateToLocation:(CLLocation*)newLocation fromLocation:(CLLocation*)oldLocation; @end @interface LocationHandler : NSObject<CLLocationManagerDelegate> { CLLocationManager *locationManager; } @property(nonatomic,strong) id<LocationHandlerDelegate> delegate; +(id)getSharedInstance; -(void)startUpdating; -(void) stopUpdating; @end
8. Now update the LocationHandler.m as follows
#import "LocationHandler.h" static LocationHandler *DefaultManager = nil; @interface LocationHandler() -(void)initiate; @end @implementation LocationHandler +(id)getSharedInstance{ if (!DefaultManager) { DefaultManager = [[self allocWithZone:NULL]init]; [DefaultManager initiate]; } return DefaultManager; } -(void)initiate{ locationManager = [[CLLocationManager alloc]init]; locationManager.delegate = self; } -(void)startUpdating{ [locationManager startUpdatingLocation]; } -(void) stopUpdating{ [locationManager stopUpdatingLocation]; } -(void)locationManager:(CLLocationManager *)manager didUpdateToLocation: (CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ if ([self.delegate respondsToSelector:@selector (didUpdateToLocation:fromLocation:)]) { [self.delegate didUpdateToLocation:oldLocation fromLocation:newLocation]; } } @end
9. Update ViewController.h as follows where we have implemented the LocationHandler delegateand create two ibOutlets.
#import <UIKit/UIKit.h> #import "LocationHandler.h" @interface ViewController : UIViewController<LocationHandlerDelegate> { IBOutlet UILabel *latitudeLabel; IBOutlet UILabel *longitudeLabel; } @end
10. Update ViewController.m as follows
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; [[LocationHandler getSharedInstance]setDelegate:self]; [[LocationHandler getSharedInstance]startUpdating]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation{ [latitudeLabel setText:[NSString stringWithFormat: @"Latitude: %f",newLocation.coordinate.latitude]]; [longitudeLabel setText:[NSString stringWithFormat: @"Longitude: %f",newLocation.coordinate.longitude]]; } @end
Output
Now when we run the application we'll get the following output.
iOS - SQLite Database
Introduction
Sqlite can be used in iOS for handling data. It just uses the sqlite queries which make it easier for those who know sql.
Steps Involved
1. Create a simple View based application.
2. Select your project file, then select targets and then add libsqlite3.dylib library in choose frameworks.
3. Now create a new file by selecting File-> New -> File... -> select Objective C class and click next
4. Name the class as DBManager with "sub class of" as NSObject.
5. Select create.
6. Now update DBManager.h as follows.
#import <Foundation/Foundation.h> #import <sqlite3.h> @interface DBManager : NSObject { NSString *databasePath; } +(DBManager*)getSharedInstance; -(BOOL)createDB; -(BOOL) saveData:(NSString*)registerNumber name:(NSString*)name department:(NSString*)department year:(NSString*)year; -(NSArray*) findByRegisterNumber:(NSString*)registerNumber; @end
8. Now update DBManager.m as follows
#import "DBManager.h" static DBManager *sharedInstance = nil; static sqlite3 *database = nil; static sqlite3_stmt *statement = nil; @implementation DBManager +(DBManager*)getSharedInstance{ if (!sharedInstance) { sharedInstance = [[super allocWithZone:NULL]init]; [sharedInstance createDB]; } return sharedInstance; } -(BOOL)createDB{ NSString *docsDir; NSArray *dirPaths; // Get the documents directory dirPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); docsDir = dirPaths[0]; // Build the path to the database file databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"student.db"]]; BOOL isSuccess = YES; NSFileManager *filemgr = [NSFileManager defaultManager]; if ([filemgr fileExistsAtPath: databasePath ] == NO) { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { char *errMsg; const char *sql_stmt = "create table if not exists studentsDetail (regno integer primary key, name text, department text, year text)"; if (sqlite3_exec(database, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK) { isSuccess = NO; NSLog(@"Failed to create table"); } sqlite3_close(database); return isSuccess; } else { isSuccess = NO; NSLog(@"Failed to open/create database"); } } return isSuccess; } - (BOOL) saveData:(NSString*)registerNumber name:(NSString*)name department:(NSString*)department year:(NSString*)year; { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { NSString *insertSQL = [NSString stringWithFormat:@"insert into studentsDetail (regno,name, department, year) values (\"%d\",\"%@\", \"%@\", \"%@\")",[registerNumber integerValue], name, department, year]; const char *insert_stmt = [insertSQL UTF8String]; sqlite3_prepare_v2(database, insert_stmt,-1, &statement, NULL); if (sqlite3_step(statement) == SQLITE_DONE) { return YES; } else { return NO; } sqlite3_reset(statement); } return NO; } - (NSArray*) findByRegisterNumber:(NSString*)registerNumber { const char *dbpath = [databasePath UTF8String]; if (sqlite3_open(dbpath, &database) == SQLITE_OK) { NSString *querySQL = [NSString stringWithFormat: @"select name, department, year from studentsDetail where regno=\"%@\"",registerNumber]; const char *query_stmt = [querySQL UTF8String]; NSMutableArray *resultArray = [[NSMutableArray alloc]init]; if (sqlite3_prepare_v2(database, query_stmt, -1, &statement, NULL) == SQLITE_OK) { if (sqlite3_step(statement) == SQLITE_ROW) { NSString *name = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 0)]; [resultArray addObject:name]; NSString *department = [[NSString alloc] initWithUTF8String: (const char *) sqlite3_column_text(statement, 1)]; [resultArray addObject:department]; NSString *year = [[NSString alloc]initWithUTF8String: (const char *) sqlite3_column_text(statement, 2)]; [resultArray addObject:year]; return resultArray; } else{ NSLog(@"Not found"); return nil; } sqlite3_reset(statement); } } return nil; }
8. Update ViewController.xib file as follows.
9. Create IBOutlets for the above text fields.
10. Create IBAction for the above buttons.
11. Update ViewController.h as follows.
#import <UIKit/UIKit.h> #import "DBManager.h" @interface ViewController : UIViewController<UITextFieldDelegate> { IBOutlet UITextField *regNoTextField; IBOutlet UITextField *nameTextField; IBOutlet UITextField *departmentTextField; IBOutlet UITextField *yearTextField; IBOutlet UITextField *findByRegisterNumberTextField; IBOutlet UIScrollView *myScrollView; } -(IBAction)saveData:(id)sender; -(IBAction)findData:(id)sender; @end
12. Update ViewController.m is as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *) nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view from its nib. } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)saveData:(id)sender{ BOOL success = NO; NSString *alertString = @"Data Insertion failed"; if (regNoTextField.text.length>0 &&nameTextField.text.length>0 && departmentTextField.text.length>0 &&yearTextField.text.length>0 ) { success = [[DBManager getSharedInstance]saveData: regNoTextField.text name:nameTextField.text department: departmentTextField.text year:yearTextField.text]; } else{ alertString = @"Enter all fields"; } if (success == NO) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: alertString message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show]; } } -(IBAction)findData:(id)sender{ NSArray *data = [[DBManager getSharedInstance]findByRegisterNumber: findByRegisterNumberTextField.text]; if (data == nil) { UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @"Data not found" message:nil delegate:nil cancelButtonTitle: @"OK" otherButtonTitles:nil]; [alert show]; regNoTextField.text = @""; nameTextField.text =@""; departmentTextField.text = @""; yearTextField.text =@""; } else{ regNoTextField.text = findByRegisterNumberTextField.text; nameTextField.text =[data objectAtIndex:0]; departmentTextField.text = [data objectAtIndex:1]; yearTextField.text =[data objectAtIndex:2]; } } #pragma mark - Text field delegate -(void)textFieldDidBeginEditing:(UITextField *)textField{ [myScrollView setFrame:CGRectMake(10, 50, 300, 200)]; [myScrollView setContentSize:CGSizeMake(300, 350)]; } -(void)textFieldDidEndEditing:(UITextField *)textField{ [myScrollView setFrame:CGRectMake(10, 50, 300, 350)]; } -(BOOL) textFieldShouldReturn:(UITextField *)textField{ [textField resignFirstResponder]; return YES; } @end
Output
Now when we run the application we'll get the following output where we can add and find student details.
iOS - Sending Email
Introduction
We can send email using the Email application of iOS device.
Steps Involved
1. Create a simple View based application.
2. Select your project file, then select targets and then add MessageUI.framework.
3. Add a button in ViewController.xib and create an action for sending email.
4. Update ViewController.h as follows.
#import <UIKit/UIKit.h> #import <MessageUI/MessageUI.h> @interface ViewController : UIViewController<MFMailComposeViewControllerDelegate> { MFMailComposeViewController *mailComposer; } -(IBAction)sendMail:(id)sender; @end
4. Update ViewController.m as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(void)sendMail:(id)sender{ mailComposer = [[MFMailComposeViewController alloc]init]; mailComposer.mailComposeDelegate = self; [mailComposer setSubject:@"Test mail"]; [mailComposer setMessageBody:@"Testing message for the test mail" isHTML:NO]; [self presentModalViewController:mailComposer animated:YES]; } #pragma mark - mail compose delegate -(void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error{ if (result) { NSLog(@"Result : %d",result); } if (error) { NSLog(@"Error : %@",error); } [self dismissModalViewControllerAnimated:YES]; } @end
Output
Now when we run the application we'll get the following output.
On clicking send Email we will get the following output.
iOS - Audio & Video
Introduction
Audio and video is quite common in latest devices. It is supported in iOS with the help ofAVFoundation.framework and MediaPlayer.framework respectively.
Steps Involved
1. Create a simple View based application.
2. Select your project file, select targets, and then we should add AVFoundation.framework andMediaPlayer.framework.
3. Add two buttons in ViewController.xib and create an action for playing audio and video respectively.
4. Update ViewController.h as follows.
#import <UIKit/UIKit.h> #import <AVFoundation/AVFoundation.h> #import <MediaPlayer/MediaPlayer.h> @interface ViewController : UIViewController { AVAudioPlayer *audioPlayer; MPMoviePlayerViewController *moviePlayer; } -(IBAction)playAudio:(id)sender; -(IBAction)playVideo:(id)sender; @end
5. Update ViewController.m as follows.
#import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } -(IBAction)playAudio:(id)sender{ NSString *path = [[NSBundle mainBundle] pathForResource:@"audioTest" ofType:@"mp3"]; audioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL: [NSURL fileURLWithPath:path] error:NULL]; [audioPlayer play]; } -(IBAction)playVideo:(id)sender{ NSString *path = [[NSBundle mainBundle]pathForResource: @"videoTest" ofType:@"mov"]; moviePlayer = [[MPMoviePlayerViewController alloc]initWithContentURL:[NSURL fileURLWithPath:path]]; [self presentModalViewController:moviePlayer animated:NO]; } @end
Note
We need to add audio and video files for ensuring that we get the expected output.
Output
Now when we run the application we'll get the following output.
When we click on play video we will get an output as shown below.
When we click play audio you will hear the audio.
iOS - File Handling
Introduction
File handling cannot be explained visually with the application and hence the key methods that are used for handling files are explained below. Please note that the application bundle only has read permission and we wont be able to modify the files. We can anyway modify documents directory of your application.
Methods used in File Handling
The list of the methods used for accessing and manipulating files are listed below. Here we have to replace the FilePath1, FilePath2 and FilePath strings to our required full file paths to get the desired action.
Check if file exists at a path
NSFileManager *fileManager = [NSFileManager defaultManager]; //Get documents directory NSArray *directoryPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectoryPath = [directoryPaths objectAtIndex:0]; if ([fileManager fileExistsAtPath:@""]==YES) { NSLog(@"File exists"); }
Comparing two file contents
if ([fileManager contentsEqualAtPath:@"FilePath1" andPath:@" FilePath2"]) { NSLog(@"Same content"); }
Check if writable, readable and executable
if ([fileManager isWritableFileAtPath:@"FilePath"]) { NSLog(@"isWritable"); } if ([fileManager isReadableFileAtPath:@"FilePath"]) { NSLog(@"isReadable"); } if ( [fileManager isExecutableFileAtPath:@"FilePath"]){ NSLog(@"is Executable"); }
Move file
if([fileManager moveItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]){ NSLog(@"Moved successfully"); }
Copy file
if ([fileManager copyItemAtPath:@"FilePath1" toPath:@"FilePath2" error:NULL]) { NSLog(@"Copied successfully"); }
Remove file
if ([fileManager removeItemAtPath:@"FilePath" error:NULL]) { NSLog(@"Removed successfully"); }
Read file
NSData *data = [fileManager contentsAtPath:@"Path"];
Write file
[fileManager createFileAtPath:@"" contents:data attributes:nil];
No comments:
Post a Comment