Thursday, December 29, 2011

Add UIBarButton item into a UIToolBar








UIToolbar *toolbar = [UIToolbar new];
toolbar.barStyle = UIBarStyleBlackTranslucent;
// create a bordered style button with custom title
UIBarButtonItem *facebook = [[[UIBarButtonItem alloc] initWithTitle:@"facebook"
                                 style:UIBarButtonItemStyleBordered   target:self           
                                 action:@selector(fbAction:)] autorelease];

UIBarButtonItem *twitter = [[[UIBarButtonItem alloc] initWithTitle:@"twitter"
                              style:UIBarButtonItemStyleBordered
      target:self
      action:@selector(twAction:)] autorelease];
NSArray *items = [NSArray arrayWithObjects
  facebook,
  twitter,
  nil];
toolbar.items = items;
// size up the toolbar and set its frame
        // please not that it will work only for views without Navigation toolbars. 
[toolbar sizeToFit];
CGFloat toolbarHeight = [toolbar frame].size.height;
CGRect mainViewBounds = self.view.bounds;
[toolbar setFrame:CGRectMake(0,0,320,40)];
[self.view addSubview:toolbar];

Tuesday, November 29, 2011

Automatic Reference Counting (ARC)

Automatic Reference Counting (ARC) for Objective-C makes memory management the job of the compiler. By enabling ARC with the new Apple LLVM compiler, you will never need to type retain or release again, dramatically simplifying the development process, while reducing crashes and memory leaks. The compiler has a complete understanding of your objects, and releases each object the instant it is no longer used, so apps run as fast as ever, with predictable, smooth performance.

Thursday, October 13, 2011

What Have You Tried?

If you’re a developer and you’re about to ask another developer a technical question (on a forum, via email, on a chat channel, or in person), you’d better be ready to answer the question “What have you tried?”
This of course isn’t specific to software developers, but that’s my field and it’s thus the area in which I’m most familiar with the issue which motivated me to write this. I’m (sadly) quite sure that it applies to your own industry too, whatever that might be.

http://mattgemmell.com/2008/12/08/what-have-you-tried/ 

Stop Activity Indicator in Status Bar ?


Implement the UIWebViewDelegate in your class file that holds the UIWebView,
and insert the following two methods:
- (void)webViewDidStartLoad:(UIWebView *)webView

- (void)webViewDidFinishLoad:(UIWebView *)webView
 In the start method, place your:
 [UIApplication sharedApplication].networkActivityIndicator
Visible = YES;
 ... and in the finish, place:
 [UIApplication sharedApplication].networkActivityIndicator
Visible = NO;

Hope this helps!

Thursday, September 08, 2011

Gdata XMl Parsing simply

This is very simple
 
xmlFileLocation = [[NSBundle mainBundle]pathForResource:@"Cars" ofType:@"xml"];
 
 NSData *xmlData = [NSData dataWithContentsOfFile:xmlFileLocation];
 
 GDataXMLDocument *xmlDocument   = [[GDataXMLDocument alloc]initWithData:xmlData options:0 error:&error];
 
NSArray *getData = [[xmlDocument rootElement]elementsForName:@"car"];
 
NSInteger type = [[(GDataXMLNode *) [[urls objectAtIndex: i] attributeForName: @ "type"] stringValue] intValue];





How to Parse a attribute using GDATA xml Parser

NSInteger type=[[(GDataXMLNode *)[[urls objectAtIndex:i] 
 attributeForName:@"type"] stringValue] intValue];
 NSInteger bit_stream=[[(GDataXMLNode *)
[[urls objectAtIndex:i]attributeForName:@"bit_stream"] 
stringValue] intValue];

Friday, August 12, 2011

How to find the hardware version in iOS


+ (NSString *)getSysInfoByName:(char *)typeSpecifier {

size_t size;

sysctlbyname(typeSpecifier, NULL, &size, NULL, 0);

char *answer = malloc(size);

sysctlbyname(typeSpecifier, answer, &size, NULL, 0);

NSString *results = [NSString stringWithCString:answer encoding: NSUTF8StringEncoding];

free(answer);

return results;

}


// to get the hardware version, we need to pass the argument hw.machine


[ClassName getSysInfoByName:"hw.machine"];


//getSysInfoByName is class method so we need to call by class name


Determine device (iPhone, iPod Touch) with iPhone SDK

NSString *deviceType = [UIDevice currentDevice].model;

if([deviceType isEqualToString:@"iPhone"])

// it is iphone
// similarly we can also check iPad,iPod, and simulator.

Tuesday, August 09, 2011

Download, Create and Display Image from URL

NSData *data=[NSData dataWithContentsOfURL:[NSURL URLWithString:URL]];

UIImage *img=[UIImage imageWithData:data];

UIImageView* imageView = [[UIImageView alloc] initWithImage:img];

[self.view addSubview:imageView];


URL may be http//...../image.jpg

Tuesday, August 02, 2011

Create JSON Object Manually without using SBJSON in iOS SDK

+(NSString *)createJSONString:(NSDictionary *) dictionary

{

NSArray *jsonKeyArray = [dictionary allKeys];

NSArray *jsonKeyValue = [dictionary allValues];

NSString *jsonString = @"{";

for (int j=0; j<[jsonKeyArray count ]; j++) {

NSDictionary *dictFromArray = [jsonKeyValue objectAtIndex:j];

NSArray *keyArray = [dictFromArray allKeys];

jsonString = [NSString stringWithFormat:@"%@\"%@\":",jsonString, [jsonKeyArray objectAtIndex:j]];

NSArray *valueArray = [dictFromArray allValues];

// to check its empty dictionary

if ([keyArray count] != 0) {

for (int i = 0; i<[keyArray count];i++) {

if (i == 0) {

jsonString =[NSString stringWithFormat:@"%@{ \"%@\": \"%@\", ",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];

}//to check lost element of single dictionary

else if((i == [keyArray count]-1) ) {

if (j != [jsonKeyArray count]-1) {

// to check whether last element combined dictionary

jsonString =[NSString stringWithFormat:@" %@ \"%@\":\"%@\" },",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];

}else

{

jsonString =[NSString stringWithFormat:@" %@ \"%@\":\"%@\" }",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];

}

}else {

jsonString =[NSString stringWithFormat:@"%@ \"%@\":\"%@\", ",jsonString,[keyArray objectAtIndex:i],[valueArray objectAtIndex:i]];

}

}

}else {

if (j != [jsonKeyArray count]-1) {

jsonString =[NSString stringWithFormat:@"%@{},",jsonString];

}else

{

jsonString =[NSString stringWithFormat:@"%@{}",jsonString];

}

}

}

jsonString =[NSString stringWithFormat:@"%@ }",jsonString];

return jsonString;

}


simple star program in c

for(int i=0;i<10;printf("\n",i++))

for(int j=0;j<=10+i;printf("%c",(j++ < 10-i)?' ':'*'));



// another method to get


BOOL var = TRUE;

int n = 3;

for(int i=0;iprintf("\n",i++))

{

var = TRUE;

for(int j=0;j<= n+i;j++)

{

if (j >= n-i)

{

if (var == TRUE) {

printf("*");

var = FALSE;

} else {

var = TRUE;

printf(" ");

}

} else {

printf(" ");

}

}

}



Calendar Custom Event Creation in iOS SDK

EKEventStore *eventStore = [[EKEventStore alloc] init];

EKEvent *event = [EKEvent eventWithEventStore:eventStore];

event.title = @"EVENT TITLE";

event.startDate = [[NSDate alloc] init];

event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];

[event setCalendar:[eventStore defaultCalendarForNewEvents]];

NSError *err;

[eventStore saveEvent:event span:EKSpanThisEvent error:&err];


Note: Please include Eventkit framework and include

#import EventKit/EventKit.h

Friday, July 22, 2011

How to Find Device Width and Height in Android SDK

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
int screen_width = display.getWidth();
int screen_height = display.getHeight();

Wednesday, July 20, 2011

How to Find Device Width and Height in iOS SDK

CGRect screenBounds = [[UIScreen mainScreen] bounds];
NSString *width=[NSString stringWithFormat:@"%g",screenBounds.size.width ];
NSString *height=[NSString stringWithFormat:@"%g",screenBounds.size.height ];
ight %@", width,height,NSStringFromCGRect(screenBounds));

Thursday, July 14, 2011

ASI HTTP Request + JSON Sample

  
ASIHTTPRequest *req = [ASIHTTPRequest requestWithURL:URL];
    req.delegate = self;
    req.userInfo = [NSDictionary dictionaryWithObject:@"initialRequest" forKey:@"type"];
    NSData *body = [jsonString  dataUsingEncoding:NSUTF8StringEncoding];
    [req appendPostData:body];
    [req startSynchronous];

Thursday, July 07, 2011

Detect device is an Android Tablet or not

public static int DISPLAY_SCREEN_WIDTH = 0;
public static int DISPLAY_SCREEN_HEIGHT = 0;
private int MAX_PHONE_WIDTH = 500;
private int MAX_PHONE_HEIGHT = 800;
private boolean isDeviceATablet() {
boolean bIsDeviceATablet = false;

Display display = ((WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
DISPLAY_SCREEN_WIDTH = display.getWidth();
DISPLAY_SCREEN_HEIGHT = display.getHeight();


if( (DISPLAY_SCREEN_WIDTH > MAX_PHONE_WIDTH) || (DISPLAY_SCREEN_HEIGHT > MAX_PHONE_HEIGHT) )
bIsDeviceATablet = true;
if(bIsDeviceATablet)
Log.i("Device is identified as an Android TABLET.");
else
Log.i("Device is identified as an Android PHONE.");

return bIsDeviceATablet;
}

UITextField delegate Methods in objectice c

1. textFieldDidBeginEditing:
Tells the delegate that editing began for the specified text field.
- (void)textFieldDidBeginEditing:(UITextField*)textField
 
2. textFieldDidEndEditing:
Tells the delegate that editing stopped for the specified text field.
- (void)textFieldDidEndEditing:( UITextField *)textField
3.textFieldShouldBeginEditing:
Asks the delegate if editing should begin in the specified text field.
- (BOOL)textFieldShouldBeginEditing:( UITextField *)textField
4.textFieldShouldClear:
Asks the delegate if the text field’s current contents should be removed.
- (BOOL)textFieldShouldClear:(UITextField *)textField
 5.textFieldShouldEndEditing:
Asks the delegate if editing should stop in the specified text field.
- (BOOL)textFieldShouldEndEditing:(UITextField *)textField
6.textFieldShouldReturn:
Asks the delegate if the text field should process the pressing of the return button.
- (BOOL)textFieldShouldReturn:(UITextField *)textField


Tuesday, July 05, 2011

How to Split string into substring in iOS Sdk

You can also split a string by a substring, using NString’s componentsSeparatedByString method.
NSString *list = @”amal, arun, balaji, dhina, guru, hari, kumar,mahes”;
NSArray *listItems = [list componentsSeparatedByString:@", "];

Thursday, June 30, 2011

Resize UIImage tutorial

-(UIImage*) scaleAndRotateImage:(UIImage*)photoimage width:(CGFloat)bounds_width height:(CGFloat)bounds_height;
{
    CGImageRef imgRef = photoimage.CGImage;

    CGFloat width = CGImageGetWidth(imgRef);
    CGFloat height = CGImageGetHeight(imgRef);

    CGAffineTrans
form transform = CGAffineTransformIdentity;
    CGRect bounds = CGRectMake(0, 0, width, height);

    bounds.size.width = bounds_width;
    bounds.size.height = bounds_height;

    CGFloat scaleRatio = bounds.size.width / width;
    CGFloat scaleRatioheight = bounds.size.height / height;
    trans
form = CGAffineTransformIdentity;

    UIGraphicsBeginImageContext(bounds.size);

    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextScaleCTM(context, scaleRatio, -scaleRatioheight);
    CGContextTranslateCTM(context, 0, -height);

    CGContextConcatCTM(context, trans
form);

    CGContextDrawImage(UIGraphicsGetCurrentContext(), CGRectMake(0, 0, width, height), imgRef);
    UIImage *imageCopy = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return imageCopy;
}

Objective -C Date Formatter Examples - stringFromDate



The format specifiers are quite straightforward, Y = year, M = month, etc. Changing the number of specifiers for a field, changes the output. For example, MMMM generates the full month name “November”, MMM results in “Nov” and MM outputs “11″.
What follows is an example to create the following date string:
Saturday November 8, 2008:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EEEE MMMM d, YYYY"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];
Here’s another example showing the current time
9:20 AM, PST:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"h:mm a, zzz"];
NSString *dateString = [dateFormat stringFromDate:today];
[dateFormat release];

More details

http://iphonedevelopertips.com/cocoa/date-formatters-examples-take-2.html

Simple NSThread Example


Threading

Sample Format:
Step .1
[NSThread detachNewThreadSelector:@selector(myMethod) toTarget:self withObject:nil];

Step .2
- (void)myMethod { NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

*** code that should be run in the new thread goes here ***


[pool release]; }

Step .3
[self performSelectorOnMainThread:@selector(myMethod) withObject:nil waitUntilDone:false];

Creating the Slider




To create a slider, you allocate it and initialize it with a frame just like any other UIKit control:

slider = [[UISliderControl alloc] initWithFrame: CGRectMake(0.0f, 32.0f, 320.0f, 20.0f)];

Next, you specify its minimum and maximum values with the setMinValue: and setMaxValue: calls. The "setShowValue" call is optional. When set to YES, it displays the current value to the right of the slider (as shown here) so the user gets instant feedback.

[slider setMaxValue:100.0f];
[slider setMinValue:0.0f];
[slider setShowValue:YES];

Now you must add a target for events. Here, I tell the slider to issue the handleSlider: method for mouse dragged events. Fortunately, the iPhone seems to use standard NextStep event equivalents, so 7 corresponds to NSRightMouseDragged, 1 to NSLeftMouseDown and 2 to NSLeftMouseUp. Since the iPhone only supports one button, the right and left gets a little confused.

[slider addTarget:self action:@selector(handleSlider:) forEvents:7];

Next, add the behavior for the message that gets called. In this example, I just write the [slider value] to a text view.

- (void) handleSlider:(id)sender{
[textView setText:[NSString stringWithFormat:@"End Value: %f", [slider value]]];

}



Reference:
// http://www.tuaw.com/2007/09/04/iphone-coding-using-the-slider/

Difference between NSString and NSMuttableString



//  Setup  two  variables  to  point  to  the  same  string
NSString * str1 = @"Hello World";

NSString * str2 = str1;


//  "Replace"  the  second  string
str2 = @"Hello ikilimnik";


//  And  list  their  current  values
NSLog(@"str1 = %@, str2 = %@", str1, str2);


Mutable strings


//  Setup  two  variables  to  point  to  the  same  string
NSMutableString * str1 = [NSMutableString stringWithString:@"Hello World"];

NSMutableString * str2 = str1;


//  "Replace"  the  second  string
[str2 setString:@"Hello ikilimnik"];


//  And  list  their  current  values
NSLog(@"str1 = %@, str2 = %@", str1, str2);


Notice when you use the immutable NSString class that the only way to "replace" a string is to create a new string and update your variable "str2" to po
int to it. 
This however doesn't affect what "str1" is pointing to, so it will still reference the original string.


In the NSMutableString example, we don't create a second string, but instead alter (mutate) the contents of 

the existing "Hello World" string. Since both variables continue to po
int to the same string object, they will both report the new value in the call to NSLog.

It's important to differentiate between a pointer variable and the actual object it points to. 

A NSString object is immutable, but that doesn't stop you from changing the value of a variable which points to a string.


The data type "NSString *" is a pointer to a NSString object, not the object itself. 

If you set a break po
int at either of the NSLog statements within the XCode debugger, you may like to check the raw value of each variable to clarify this.


Reference:


http:
//www.cocoadev.com/index.pl?NSString

http:
//stackoverflow.com/questions/1805442/nsstring-immutable-allows-to-change-its-values

Wednesday, June 29, 2011

how to use SwipeGestureRegognizer

// add the below code in viewDidLoad  method
swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self
                                                                action:@selector(swipeMethod:)];
    swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight | UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizer];

-(void)swipeMethod: (UISwipeGestureRecognizer *) sender
{
NSLog(@"swipe event detected");

}

// if we need means we use separate swipegesture for left, right, up and down direction

Touch (XY) detection in iPhone

- (void) touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event
{
    startTime = [NSDate timeIntervalSinceReferenceDate];
     pt = [[touches anyObject] locationInView:self.view];
    NSLog(@"%d,%d x y",pt.x,pt.y);
  }

Regarding This Blog

This Blog is only use for study related . if you have any question just update me i will help you .

Tuesday, June 28, 2011

To Rotate a view

       //to rotae a view
        [UIView beginAnimations:@"View Flip" context:nil];
        [UIView setAnimationDuration:0.5f];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
       
        self.view.transform = CGAffineTransformIdentity;
        self.view.transform = CGAffineTransformMakeRotation(180);// angle of rotation
        self.view.bounds = CGRectMake(0.0f, 0.0f, 480.0f, 320.0f);
        self.view.center = CGPointMake(160.0f, 240.0f);
        NSLog(@"end");
        [UIView commitAnimations];

Monday, June 27, 2011

Milli Seconds calculation

       // Start timer
    NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];
   
      // Do something
    for(double i=0; i < 1000000; i++ );
   
       // Stop timer
    NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate];
   
       // Get the elapsed time in milliseconds
    NSTimeInterval elapsedTime = (endTime - startTime) * 1000;

       // Send it to the Console
    NSLog(@"Elapsed time in ms: %f", elapsedTime);

Thursday, June 23, 2011

Memory Management Simple Example

// string1 will be released automatically
  NSString* string1 = [NSString string];
// must release this when done
  NSString* string2 = [[NSString alloc] init]; [string2 release];

Network Activity Status Indicator


UIApplication* app = [UIApplication sharedApplication];
app.networkActivityIndicatorVisible = YES;
// to stop it, set this to NO

Json Parsing Request

NSDictionary *o1 = [NSDictionary dictionaryWithObjectsAndKeys:
                       
                        @"some value", @"key1",
                       
                        @"another value", @"key2",
                       
                        nil];
   
   
    NSDictionary *o2 = [NSDictionary dictionaryWithObjectsAndKeys:
                       
                        @"yet another value", @"key1",
                       
                        @"some other value", @"key2",
                       
                        nil];
   
   
    NSArray *array = [NSArray arrayWithObjects:o1, o2, nil];
   
   
    NSString *jsonString = [array JSONRepresentation];
   
    NSLog(@"%@",jsonString);
   
    NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://sample.com"]];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
   
    NSLog(@"%@",connection);



Note:

Before write code you have to include JSON Files. it is available

If you have any doubt ask me...

Thursday, April 21, 2011

iPhone Developer

Hi Friends,

i am going to use this blog for iPhone development. all questions and answers available. so give me your support to this blog

Swift Operators - Basic Part 3 (Range operators in swift)

Range Operators: Closed Range operators  Half-Open Range Operators One-Sided Ranges Closed Range Operators:  a...b It defines...