My Blog List

Android FirstAid Coding

A Small Help From a Small Heart
Powered by Blogger.

A software professional, who still likes to code, likes to blog and loves gadgets.

Tuesday, 28 May 2013

Showing UIPickerView inside UIPopoverController


ViewController.h
=============
#import <UIKit/UIKit.h>


@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>{
    int selectedProductTypeSrcIndex;  
    NSString *selectedProductType;  
    IBOutlet UIButton *productTypeOption;  
}
@property(nonatomic,retain) NSArray *productTypeSrc;
@property(nonatomic,retain) UIPickerView *myPickerView;
@property(nonatomic,retain) UIPopoverController *popoverController;
- (IBAction)showOptionAction:(id)sender;

@end



ViewController.m
================

//
// ViewController.m
// PickerDemo
//
// Created by Rajendra on 27/05/13.
// Copyright (c) 2013 RajuAndroid.blogspot.com. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


@synthesize myPickerView,popoverController;
@synthesize productTypeSrc;
- (void)viewDidLoad

{

[super viewDidLoad];
self.productTypeSrc = [NSArray arrayWithObjects:@"Collison Damage Waive",@"Deposit Waiver",@"Excess Reduction Waiver",@"Malaysian Travel Charges Waiver",@"Penalty Waiver",nil];
selectedProductTypeSrcIndex=0;

}

- (IBAction)showOptionAction:(id)sender{
UIView *masterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 300, 260)];
UIToolbar *pickerToolbar = [self createPickerToolbarWithTitle:@"Title"];
[pickerToolbar setBarStyle:UIBarStyleBlackTranslucent];
[masterView addSubview:pickerToolbar];
CGRect pickerFrame = CGRectMake(0, 40, 300, 216);
UIPickerView *myPicker = [[UIPickerView alloc] initWithFrame:pickerFrame];
[myPicker setDataSource: self];
[myPicker setDelegate: self];
myPicker.tag=1;
[myPicker selectRow:0 inComponent:0 animated:NO];
[myPicker setShowsSelectionIndicator:YES];
self.myPickerView=myPicker;
[masterView addSubview:myPicker];
UIViewController *viewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
viewController.view = masterView;
viewController.contentSizeForViewInPopover = viewController.view.frame.size;
self.popoverController =[[UIPopoverController alloc] initWithContentViewController:viewController];
UIButton *button = (UIButton *)sender;
[self.popoverController presentPopoverFromRect:button.bounds
inView:button
permittedArrowDirections:UIPopoverArrowDirectionDown
animated:YES];

}

- (UIToolbar *)createPickerToolbarWithTitle:(NSString *)title {

CGRect frame = CGRectMake(0, 0, 300, 44);
UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:frame];
pickerToolbar.barStyle = UIBarStyleBlackOpaque;
NSMutableArray *barItems = [[NSMutableArray alloc] init];
UIBarButtonItem *cancelBtn = [self createButtonWithType:UIBarButtonSystemItemCancel target:self action:@selector(actionPickerCancel:)];
[barItems addObject:cancelBtn];
UIBarButtonItem *flexSpace = [self createButtonWithType:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

[barItems addObject:flexSpace];
if (title){
UIBarButtonItem *labelButton = [self createToolbarLabelWithTitle:title];
[barItems addObject:labelButton];
[barItems addObject:flexSpace];
}
UIBarButtonItem *doneButton = [self createButtonWithType:UIBarButtonSystemItemDone target:self action:@selector(actionPickerDone:)];
[barItems addObject:doneButton];
[pickerToolbar setItems:barItems animated:YES];
return pickerToolbar;

}

- (IBAction)actionPickerDone:(id)sender {

//[self notifyTarget:self.target didSucceedWithAction:self.successAction origin:[self storedOrigin]];

if (self.popoverController && self.popoverController.popoverVisible)
[self.popoverController dismissPopoverAnimated:YES];

}

- (IBAction)actionPickerCancel:(id)sender {

if (self.popoverController && self.popoverController.popoverVisible)
[self.popoverController dismissPopoverAnimated:YES];

}

- (UIBarButtonItem *)createToolbarLabelWithTitle:(NSString *)aTitle {

UILabel *toolBarItemlabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 180,30)];
[toolBarItemlabel setTextAlignment:UITextAlignmentCenter];
[toolBarItemlabel setTextColor:[UIColor whiteColor]];
[toolBarItemlabel setFont:[UIFont boldSystemFontOfSize:16]];
[toolBarItemlabel setBackgroundColor:[UIColor clearColor]];
toolBarItemlabel.text = aTitle;
UIBarButtonItem *buttonLabel = [[UIBarButtonItem alloc]initWithCustomView:toolBarItemlabel];
return buttonLabel;

}

- (UIBarButtonItem *)createButtonWithType:(UIBarButtonSystemItem)type target:(id)target action:(SEL)buttonAction {

return [[UIBarButtonItem alloc] initWithBarButtonSystemItem:type target:target action:buttonAction];

}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

{

return 1;

}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;

{

if ([pickerView tag] == 1) {
return [self.productTypeSrc count];
}
return 0;

}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;

{
if ([pickerView tag] == 1) {
return [self.productTypeSrc objectAtIndex:row];

}

return @"";

}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component

{

if ([pickerView tag] == 1) {
selectedProductTypeSrcIndex=row;
selectedProductType=[self.productTypeSrc objectAtIndex:selectedProductTypeSrcIndex];
[productTypeOption setTitle:selectedProductType forState:UIControlStateNormal];

}

}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

@end


 
 

Wednesday, 1 May 2013

How to store custom objects in NSUserDefaults in Iphone

Situation
=============

  • I am storing Custom object in NSMutableArray
  • then storing NSMutableArray into NSMutableDictionary.
  • Where Key of NSMutableDictionary is a unique_foldername(NSString) and value of NSDictionary is a NSMutableArray.
Question
==============
  • Now how can i store NSMutableDictionary in NSUserDefaults ?
  • Now how can i retrieve NSMutableDictionary from NSUserDefaults?
Solution
==============

DocumentVo.h
-----------------
#import <UIKit/UIKit.h>

@interface DocumentVo : NSObject{
    NSString *docName,*docUpdatedTime,*docImage;
    int docCount;
}
@property (nonatomic, retain) NSString *docName,*docUpdatedTime,*docImage;
@property (nonatomic) int docCount;
@end

DocumentVo.m
----------------- 
#import "DocumentVo.h"

@implementation DocumentVo
@synthesize docName,docUpdatedTime,docCount,docImage;

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.docName forKey:@"docName"];
    [encoder encodeObject:self.docUpdatedTime forKey:@"docUpdatedTime"];
   
    [encoder encodeInt:self.docCount forKey:@"docCount"];
    [encoder encodeObject:self.docImage forKey:@"docImage"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.docName = [decoder decodeObjectForKey:@"docName"];
        self.docUpdatedTime = [decoder decodeObjectForKey:@"docUpdatedTime"];
        self.docCount = [decoder decodeIntForKey:@"docCount"];
        self.docImage = [decoder decodeObjectForKey:@"docImage"];
    }
    return self;
}
- (void) dealloc {
    [docName release];
    [docUpdatedTime release];
    //[docCount release];
    [docImage release];
    [super dealloc];
}

@end
 

 Saving Object
---------------------

    NSString *rootFolderName;
    NSUserDefaults *defauktCenter = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary *allFolderWithImageDict=[NSMutableDictionary dictionary];
    NSMutableDictionary *resultDictionary = [NSKeyedUnarchiver unarchiveObjectWithData:respData];
    NSMutableArray *docArray=[[NSMutableArray alloc] init];   
    DocumentVo *docVo=[[DocumentVo alloc] init];
    docVo.docCount=1;
    docVo.docName=@"FolderName";
    docVo.docUpdatedTime=@"12:23";
    docVo.docImage=@"FolderName/myfilename";
    [docArray addObject:docVo];  
  
    [allFolderWithImageDict setValue:docArray forKey:rootFolderName];  
    NSData *myEncodedObject = [NSKeyedArchiver     archivedDataWithRootObject:allFolderWithImageDict];  
    [defauktCenter setValue:myEncodedObject forKey:@"FolderImageDict"];
    [defauktCenter synchronize];


  Retrieving Object

--------------------------
    NSData *respData1 = [[NSUserDefaults standardUserDefaults] objectForKey:@"FolderImageDict"];
    NSMutableDictionary *resultDictionary1 = [NSKeyedUnarchiver unarchiveObjectWithData:respData1];
 
    NSArray * array= [resultDictionary1 objectForKey:rootFolderName] ;
    DocumentVo *docVo1=[array objectAtIndex:0];
    NSLog(@"docVo.docCount==%d",docVo1.docCount);
    NSLog(@"docVo.docName==%@",docVo1.docName);
    NSLog(@"docVo.docUpdatedTime==%@",docVo1.docUpdatedTime);
    NSLog(@"docVo.docImage==%@",docVo1.docImage);





 

Monday, 29 April 2013

UIMenuController in iphone

NOTE:
UIMenuController will only work if it becomes the first responder

- (void)viewDidLoad
{
    [super viewDidLoad];  
    UIBarButtonItem *addJobButton = [[UIBarButtonItem alloc] initWithTitle:@"Add Contacts" style:UIBarButtonSystemItemAdd
                                                                    target:self action:@selector(setAddContactTapped:event:)];
    self.navigationItem.rightBarButtonItem = addJobButton;
    [addJobButton release];
}
-(void)setAddContactTapped:(id)sender event:(UIEvent*)event{
    [self becomeFirstResponder];
     /*get the view from the UIBarButtonItem*/
    UIView *buttonView=[[event.allTouches anyObject] view];
    CGRect buttonFrame=[buttonView convertRect:buttonView.frame toView:self.view];
   
    UIMenuController *menuController = [UIMenuController sharedMenuController];
    UIMenuItem *personMenuItem = [[UIMenuItem alloc] initWithTitle:@"Person" action:@selector(newPerson:)];
    UIMenuItem *companyMenuItem = [[UIMenuItem alloc] initWithTitle:@"Company" action:@selector(newCompany:)];
   
   // NSAssert([self becomeFirstResponder], @"Sorry, UIMenuController will not work with %@ since it cannot become first responder", self);
    menuController.menuItems = [NSArray arrayWithObjects: personMenuItem, companyMenuItem, nil];  
    [menuController setTargetRect:buttonFrame inView:self.view];
    [menuController setMenuVisible:YES animated:YES];
    [personMenuItem release];
    [companyMenuItem release];      
}

- (void) newPerson: (UIMenuController*) sender
{
 //Add you logic
}
- (void) newCompany: (UIMenuController*) sender
{ 
    //Add your logic
}

- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
    BOOL can = [super canPerformAction:action withSender:sender];
    if (action == @selector(
newPerson:) || action == @selector(newCompany:))
    {
        can = YES;
    }
    if (action == @selector(copy:))
    {
        can = NO;
    }
   return can;
}
- (BOOL) canBecomeFirstResponder {
    return YES;
}


Showing Activity Indicator Within UIAlertview in Iphone

ViewController.h
================

@interface ViewController : UIViewController{
    UIAlertView *alertLoader;
}

@end

ViewController.m
================

- (void)viewDidLoad
{
    [super viewDidLoad];  
    [self methodtocallWebservices];
}
-(void)methodtocallWebservices{   
    alertLoader = [[UIAlertView alloc] initWithTitle:@"" message:@"Please Wait..." delegate:self cancelButtonTitle:nil otherButtonTitles:nil];
    alertLoader.tag=1;
    [alertLoader show];   
}
- (void)didPresentAlertView:(UIAlertView *)alertView
{  
    if (alertView.tag== 1) {
        UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];       
        indicator.center = CGPointMake(alertView.bounds.size.width/2, alertView.bounds.size.height/3 * 2);       
        [indicator startAnimating];
        [alertView addSubview:indicator];       
        NSString *hostStr = @"@"http://rajuandroid.blogspot.com/api/contact_name_json";       
        NSURL *url = [[NSURL alloc] initWithString:hostStr];
        NSLog(@"login url:  %@",url);       
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
        [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
        [url release];
    }   
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
  //  [self.receivedData appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [self stopLoading];
    //[self handleError:error];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
    [self stopLoading];  
}
-(void)stopLoading
{
    dispatch_async(dispatch_get_main_queue(), ^{
        [alertLoader dismissWithClickedButtonIndex:0 animated:YES];
        [alertLoader release];
    });
}



Friday, 26 April 2013

How to add button in navigation bar in iphone/ipad/IOS



Adding system bar button

UIBarButtonItem *saveButton = [[UIBarButtonItem alloc]                             initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
                               target:self 
                                style:UIBarButtonItemStyleBordered
                               action:@selector(postNewCase:)];
self.navigationItem.rightBarButtonItem = saveButton;
[saveButton release];

-(IBAction)postNewCase:(id)sender {
}

Adding image bar button

UIImage *buttonImage = [UIImage imageNamed:@"home_icon.png"];
UIButton *forwardButton = [UIButton      buttonWithType:UIButtonTypeCustom];
[forwardButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
forwardButton.frame = CGRectMake(0, 0, buttonImage.size.width, buttonImage.size.height);
[forwardButton addTarget:self action:@selector(postNewCase:)
           forControlEvents:UIControlEventTouchUpInside];
   
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:forwardButton];
   

Adding plain button
UIBarButtonItem *postButton = [[UIBarButtonItem alloc] 
                               initWithTitle:@"Post"                                            
                               style:UIBarButtonItemStyleBordered 
                               target:self 
                               action:@selector(postNewCase:)];
self.navigationItem.rightBarButtonItem = postButton;
[postButton release];

Add background image to navigation bar

[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed: @"navigationBar.png"] forBarMetrics:UIBarMetricsDefault];

Add logo to navigation bar
 UIImage *image = [UIImage imageNamed: @"new_kj_logo-150.png"];
    UIImageView *imageView = [[UIImageView alloc] initWithImage: image];
   
    self.navigationItem.titleView = imageView;

Hide Navigation default back button
 self.navigationItem.hidesBackButton = YES;




Wednesday, 3 April 2013

How to handle null vallue in json iphone

id displayNameTypeValue = [object objectForKey:@"address"];
NSString *displayNameType = @"";
if (displayNameTypeValue != [NSNull null])
   displayNameType = (NSString *)displayNameTypeValue;
 
 
 
 

Tuesday, 2 April 2013

Camera Sample Code in Iphone

AppDelegate.h
=========
//
//  AppDelegate.h
//  Genius
//
//  Created by Rajendra on 02/04/13.
//  Copyright (c) 2013 __Rajuandroid.blogspot.com__. All rights reserved.
//

#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) UINavigationController *navController;
@property (strong, nonatomic) ViewController *viewController;

@end


AppDelegate.m
============
//
//  AppDelegate.m
//  Genius
//
//  Created by Rajendra on 02/04/13.
//  Copyright (c) 2013 __Rajuandroid.blogspot.com__. All rights reserved.
//

#import "AppDelegate.h"

#import "ViewController.h"

@implementation AppDelegate
@synthesize navController;
@synthesize window = _window;
@synthesize viewController = _viewController;

- (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];
    navController = [[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = self.navController;
    [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
//  Genius
//
//  Created by Rajendra on 02/04/13.
//  Copyright (c) 2013 __Rajuandroid.blogspot.com__. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>{
    UIBarButtonItem *cameraButton;
}
@property (nonatomic, retain) UIImage* attachedImage;
@property (nonatomic, retain) UIBarButtonItem *cameraButton;
@end
 

ViewController.m
================

//
//  ViewController.m
//  Genius
//
//  Created by Rajendra on 02/04/13.
//  Copyright (c) 2013 __Rajuandroid.blogspot.com__. All rights reserved.
//
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize attachedImage,cameraButton;
- (void)viewDidLoad
{
    [super viewDidLoad];
   
    cameraButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"camera.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(showActionSheet:)];
   
    self.navigationItem.rightBarButtonItem = cameraButton;
    [cameraButton release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
-(IBAction)showActionSheet:(id)sender {
    UIActionSheet *popupQuery = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take Photo", @"Choose Photo", nil];
    popupQuery.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [popupQuery showFromToolbar:(UIToolbar *)self.view];
    [popupQuery release];
}
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    UIImagePickerController* imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
   
    if (buttonIndex == 0) {
        if ([UIImagePickerController isSourceTypeAvailable:
             UIImagePickerControllerSourceTypeCamera])
        {
            imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            [self presentModalViewController:imagePicker animated:YES];
           
        }else {
            UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"" message:@"Camera is not available"
                                                                  delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertsuccess show];
        }
    } else if (buttonIndex == 1) {
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentModalViewController:imagePicker animated:YES];
       
    }
    else if (buttonIndex == 2) {
        //cancel clicked
    }
   
}


#pragma mark - pictures

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    self.attachedImage = nil;
    [self dismissModalViewControllerAnimated:YES];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   
    [picker dismissModalViewControllerAnimated:YES];
   
    UIImage *image = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
   
    self.attachedImage = image;
   
    dispatch_async(dispatch_get_main_queue(), ^{
        CGFloat scale = [self.view.window.screen scale];
        CGSize size = CGSizeMake(30., 30.);
        UIGraphicsBeginImageContextWithOptions(size, YES, scale);
        CGContextSetInterpolationQuality(UIGraphicsGetCurrentContext(), kCGInterpolationHigh);
        [image drawInRect:CGRectMake(0., 0., size.width, size.height)];
        UIImage* thumb = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
       
        cameraButton.image = thumb;
       
    });
}



@end