Sunday, November 2, 2014

iOS Tutorial - Part 23 - UIAlertController, UIImagePickerController

UIAlertController, UIImagePickerController


Video Description 

UIAlertController

Displays an alert message to the user. This class replaces the UIActionSheet and UIAlertView classes for displaying alerts.

Steps to create UIAlertController

1- Initialize allertController with the specified title, message and the style you want.
    UIAlertController *alertCtrl = [UIAlertController alertControllerWithTitle:@"Alert Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleActionSheet];
2- Create actionAllert with specified title, style and handle the event when user taps on it
    UIAlertAction *buttonOnAlertCtrl = [UIAlertAction actionWithTitle:@"Button Title" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action)
                                                    {
                                                        //Handle Event
                                                    }];
3- Add the button to the allertController
[alertCtrl addAction:buttonOnAlertCtrl];
4- Show it to the screen
[self presentViewController:self.alertCtrl animated:YES completion:nil];

UIImagePickerController

You can use UIImagePickerController to get image from PhotoLibrary or Camera

Steps to get image from Camera

1- Create a property like bellow to access UIImagePickerController anywhere inside of your class @property (strong, nonatomic) UIImagePickerController *imagePicker; 2- Initialize and allocate memory
self.imagePicker = [[UIImagePickerController alloc] init];
//Set delegate method equal to self
self.imagePicker.delegate = self;
//Set source type (Here we choose camera)
self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
//Present the camera to the screen
[self presentViewController:self.imagePicker animated:YES completion:nil];
2- Add delegate names (UIImagePickerControllerDelegate, UINavigationControllerDelegate) in front of the interface
@interface ViewController () 
3- Implement UIImagePickerControllerDelegate method
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],1);
    UIImage *img = [[UIImage alloc] initWithData:dataImage];
    //img is the picture that user captured with the camera, you can do whatever you want with this picture
    //Add your own implementation here
}

Get get image from Photo Library

The steps are exactly like the steps for getting image from camera, except the source type. You should use the following line instead of line 4 of step 2:
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;

Write Macro to compile different block of code for simulator vs. actual device

If we want to tell the compiler to run a block of code if its simulator and other block of code if it's on actual device, we can use the following if else statement: #if TARGET_IPHONE_SIMULATOR //Put the block of code that you want to be executed if it's running on the simulator #elif TARGET_OS_IPHONE //Put the block of code that you want to be executed if it's running on the actual device #endif

All of the code for this tutorial

#import "ViewController.h"

@interface ViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (strong, nonatomic) UIAlertController *alertCtrl;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setupAlertCtrl];
}

- (void) setupAlertCtrl
{
    self.alertCtrl = [UIAlertController alertControllerWithTitle:@"Select Image"
                                                         message:nil
                                                  preferredStyle:UIAlertControllerStyleActionSheet];
    //Create an action
    UIAlertAction *camera = [UIAlertAction actionWithTitle:@"Camera"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action)
                                                    {
                                                        [self handleCamera];
                                                    }];
    UIAlertAction *imageGallery = [UIAlertAction actionWithTitle:@"Image Gallery"
                                                     style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction *action)
                                                    {
                                                        [self handleImageGallery];
                                                    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"Cancel"
                                                           style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction *action)
                                   {
                                       [self dismissViewControllerAnimated:YES completion:nil];
                                   }];

    
    //Add action to alertCtrl
    [self.alertCtrl addAction:camera];
    [self.alertCtrl addAction:imageGallery];
    [self.alertCtrl addAction:cancel];
    
    
}

- (IBAction)selectImagePressed:(UIButton *)sender
{
    [self presentViewController:self.alertCtrl animated:YES completion:nil];
}

- (void)handleCamera
{
#if TARGET_IPHONE_SIMULATOR
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Error"
                                                                   message:@"Camera is not available on simulator"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *ok = [UIAlertAction actionWithTitle:@"OK"
                                                 style:UIAlertActionStyleDefault
                                               handler:^(UIAlertAction *action)
                                                {
                                                    [self dismissViewControllerAnimated:YES completion:nil];
                                                }];
    
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
#elif TARGET_OS_IPHONE
    //Some code for iPhone
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.delegate = self;
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:self.imagePicker animated:YES completion:nil];

#endif
}

- (void)handleImageGallery
{
    self.imagePicker = [[UIImagePickerController alloc] init];
    self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    self.imagePicker.delegate = self;
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    NSData *dataImage = UIImageJPEGRepresentation([info objectForKey:@"UIImagePickerControllerOriginalImage"],1);
    UIImage *img = [[UIImage alloc] initWithData:dataImage];
    [self.imageView setImage:img];
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
    
}

Download

Download this App from here

3 comments:

  1. this is not working showing error .
    ShowImage[682:60b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present a nil modal view controller on target .'
    *** First throw call stack:
    (0x2eacbfd3 0x396bdccf 0x313cf9f9 0xa0889 0x3131d057 0x3131cff7 0x3131cfd1 0x31308737 0x3131ca4f 0x3131c721 0x313176eb 0x312ec8ed 0x312eaf97 0x2ea9725b 0x2ea9672b 0x2ea94f1f 0x2e9fff4f 0x2e9ffd33 0x33906663 0x3134b16d 0xa10e1 0x39bcaab7)
    libc++abi.dylib: terminating with uncaught exception of type NSException
    (lldb)

    ReplyDelete
    Replies
    1. Sorry about that. Did you downloaded the app and it shows this error? Or you followed the tutorial and wrote it by yourself?

      Delete
  2. Hey!
    Thank you for your tutorials. Where can I download (if it is available) your very handy presentation file, that you refer to in tutorials?
    Thanks in advance.

    ReplyDelete