Reader Level:
Articles

Camera in iPhone

By Sachin Bhardwaj on December 06, 2012
In this article I will explain how to implement a camera in an iPhone.
  • 0
  • 0
  • 2260
Download Files:
 

Introduction

In this article I will create a Single View application. Here I use an image view and two buttons from outlet. In this app I will implement a Camera for an iPhone and to watch Clicked Photos we implement an image gallery path from which we pick an image and watch it. But this app does not work in the iPhone Simulator. If we test this app in a device then it will successfully Run.

To understand it we use the following.

Step 1

Here first we add the framework "CoreImage.framework" which is required to implement the Camera.

To import this framework we use the following.

Step 2

Click on the project and select Build Phase.

Build-phase-in-iphone.jpg

Step 3

Click on the "+" icon to add the framework.

add frameworrk-in-iPhone.jpg

Step 4

Now select the CoreImage framework and click on the add button.

framework-in-iPhone.jpg

Step 5

To pick an image from the image gallery we need MobileCoreService framework, so here we import it to the project.

MobileCoreServiceframework-in-iPhone.jpg

Step 6

Now we write the code for each class.

camAppDelegate.h

//

//  camAppDelegate.h

//  Camera

//

//  Created by Sachin Bhardwaj on 06/12/12.

//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

@class camViewController;

@interface camAppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) camViewController *viewController;

@end

camAppDelegate.m

//

//  camAppDelegate.m

//  Camera

//

//  Created by Sachin Bhardwaj on 06/12/12.

//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//

#import "camAppDelegate.h"

#import "camViewController.h"

@implementation camAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    // Override point for customization after application launch.

    self.viewController = [[camViewController alloc] initWithNibName:@"camViewController" 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

camViewController.h

//

//  camViewController.h

//  Camera

//

//  Created by Sachin Bhardwaj on 06/12/12.

//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//

#import <UIKit/UIKit.h>

#import <MobileCoreServices/MobileCoreServices.h>

@interface camViewController : UIViewController<UIImagePickerControllerDelegate,

UINavigationControllerDelegate>

@property (nonatomic) BOOL newMedia;

@property (nonatomic, strong) IBOutlet UIImageView *imageView;

- (IBAction)Click;

- (IBAction)Photos;

@end

camViewController.m

//

//  camViewController.m

//  Camera

//

//  Created by Sachin Bhardwaj on 06/12/12.

//  Copyright (c) 2012 Sachin Bhardwaj. All rights reserved.

//
 

#import "camViewController.h"

@interface camViewController ()

@end

@implementation camViewController

@synthesize imageView, newMedia;

- (void) Click

{

    

    NSLog(@"It's working");

    if ([UIImagePickerController isSourceTypeAvailable:

         UIImagePickerControllerSourceTypeCamera])

    {

        UIImagePickerController *imagePicker =

        [[UIImagePickerController alloc] init];

        imagePicker.delegate = self;

        imagePicker.sourceType =

        UIImagePickerControllerSourceTypeCamera;

        imagePicker.mediaTypes = [NSArray arrayWithObjects:

                                  (NSString *) kUTTypeImage,

                                  nil];

        imagePicker.allowsEditing = NO;

        [self presentModalViewController:imagePicker

                                animated:YES];

        

        

        newMedia = YES;

    }

}

- (void) Photos

{

    if ([UIImagePickerController isSourceTypeAvailable:

         UIImagePickerControllerSourceTypeSavedPhotosAlbum])

    {

        UIImagePickerController *imagePicker =

        [[UIImagePickerController alloc] init];

        imagePicker.delegate = self;

        imagePicker.sourceType =

        UIImagePickerControllerSourceTypePhotoLibrary;

        imagePicker.mediaTypes = [NSArray arrayWithObjects:

                                  (NSString *) kUTTypeImage,

                                  nil];

        imagePicker.allowsEditing = NO;

        [self presentModalViewController:imagePicker animated:YES];

        newMedia = NO;

    }

}

-(void)imagePickerController:(UIImagePickerController *)picker

didFinishPickingMediaWithInfo:(NSDictionary *)info

{

    NSString *mediaType = [info

                           objectForKey:UIImagePickerControllerMediaType];

    [self dismissModalViewControllerAnimated:YES];

    if ([mediaType isEqualToString:(NSString *)kUTTypeImage]) {

        UIImage *image = [info

                          objectForKey:UIImagePickerControllerOriginalImage];

        

        imageView.image = image;

        if (newMedia)

            UIImageWriteToSavedPhotosAlbum(image,

                                           self,

                                           @selector(image:finishedSavingWithError:contextInfo:),

                                           nil);

    }

    else if ([mediaType isEqualToString:(NSString *)kUTTypeMovie])

    {

// Code here to support video if enabled

}

}

-(void)image:(UIImage *)image

finishedSavingWithError:(NSError *)error

 contextInfo:(void *)contextInfo

{

    if (error) {

        UIAlertView *alert = [[UIAlertView alloc]

                              initWithTitle: @"Save failed"

                              message: @"Failed to save image"\

                              delegate: nil

                              cancelButtonTitle:@"OK"

                              otherButtonTitles:nil];

        [alert show];

    }

}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker

{

    [self dismissModalViewControllerAnimated:YES];

}

- (void)didReceiveMemoryWarning

{

    [super didReceiveMemoryWarning];

    // Release any cached data, images, etc that aren't in use.

}

#pragma mark - View lifecycle

- (void)viewDidLoad

{

    [super viewDidLoad];

// Do any additional setup after loading the view, typically from a nib.

}

- (void)viewDidUnload

{

    [super viewDidUnload];

    // Release any retained subviews of the main view.

    // e.g. self.myOutlet = nil;

    self.imageView = nil;    

}

- (void)viewWillAppear:(BOOL)animated

{

    [super viewWillAppear:animated];

}

- (void)viewDidAppear:(BOOL)animated

{

    [super viewDidAppear:animated];

}

- (void)viewWillDisappear:(BOOL)animated

{

[super viewWillDisappear:animated];

}

- (void)viewDidDisappear:(BOOL)animated

{

[super viewDidDisappear:animated];

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

    // Return YES for supported orientations

    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);

}

@end

twitterappViewController.xib

Step 8

Now we check the connection Outlet String. To do that we click on file owner and press the right mouse button.

outlet-connection-in-iPhone.jpg

Step 9

Finally we click on the run button to show the output.

Step 10

Output 1 in iPhone:

Click on the Camera Button.

camera-output-in-iphone.jpg

It does not initialize the camera in the simulator but it still works in the iPhone device. Here it will show output in the xcode output window.

Output 2 in iPhone

To watch captured Photos click on the Go To Photos Button.

output1-in-iPhone.jpg

Output 3 in iPhone

Now choose an image from the Image Gallery. To do that click on the saved photos.

output2-in-iPhone.jpg

Output 4 in iPhone:

output3-in-iPhone.jpg

Sachin Bhardwaj

Sachin Bhardwaj is a software developer working with Apple technologies including Xcode, iOS, iPhone, iPad, iPod and Mobile app store. 

COMMENT USING

Trending up