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.

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