Thursday, 20 December 2012

Animating/Sliding In a UIelement


//in .h

IBOutlet UIImageView *onenewChange;
IBOutlet UIImageView *perfectWeekendShop;


//In view didload



 CGRect mensImageFrame = onenewChange.frame;
    CGRect temp = onenewChange.frame;
    onenewChange.frame = CGRectMake(768, temp.origin.y ,temp.size.width, temp.size.height);
    
    // CGRect bigImageFrame = onenewView.frame;
    // temp = onenewView.frame;
    //onenewView.frame = CGRectMake(768, temp.origin.y ,temp.size.width, temp.size.height);
    
    // CGRect feastImageFrame = perfectWeekendShop.frame;
    //temp = perfectWeekendShop.frame;
    //perfectWeekendShop.frame = CGRectMake(0 - temp.size.width, temp.origin.y ,temp.size.width, temp.size.height);
    
    

    // CGRect inLondonImageFrame = inLondon_Image.frame;
    //temp = inLondon_Image.frame;
    // inLondon_Image.frame = CGRectMake(768, temp.origin.y ,temp.size.width, temp.size.height);
    
    // bottomBar_Image.alpha = 0 ;
    
    
    [UIView animateWithDuration:1.0
                          delay:1.0
                        options:UIViewAnimationOptionCurveEaseOut
                     animations:^{
                         
                         onenewChange.frame = mensImageFrame;
                         // onenewView.frame = bigImageFrame;
                         //perfectWeekendShop.frame = feastImageFrame;
                         
                     }
                     completion:^(BOOL completed) {
                         
                     }];

TextField and TextView Moving Up while typing

At top.before #import.


CGFloat animatedDistance;
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat MINIMUM_SCROLL_FRACTION = 0.2;
static const CGFloat MAXIMUM_SCROLL_FRACTION = 0.8;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 216;
static const CGFloat LANDSCAPE_KEYBOARD_HEIGHT = 162;

//any where in .m


- (void)textViewDidBeginEditing:(UITextView *)textView{
    CGRect textFieldRect =
    [self.view.window convertRect:textView.bounds fromView:textView];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];
    
    
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator =
    midline - viewRect.origin.y
    - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];

}

- (void)textViewDidEndEditing:(UITextView *)textView{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField
{
   // signup.enabled=NO;
    CGRect textFieldRect =
    [self.view.window convertRect:textField.bounds fromView:textField];
    CGRect viewRect =
    [self.view.window convertRect:self.view.bounds fromView:self.view];
    
    
    CGFloat midline = textFieldRect.origin.y + 0.5 * textFieldRect.size.height;
    CGFloat numerator =
    midline - viewRect.origin.y
    - MINIMUM_SCROLL_FRACTION * viewRect.size.height;
    CGFloat denominator =
    (MAXIMUM_SCROLL_FRACTION - MINIMUM_SCROLL_FRACTION)
    * viewRect.size.height;
    CGFloat heightFraction = numerator / denominator;
    
    if (heightFraction < 0.0)
    {
        heightFraction = 0.0;
    }
    else if (heightFraction > 1.0)
    {
        heightFraction = 1.0;
    }
    
    UIInterfaceOrientation orientation =
    [[UIApplication sharedApplication] statusBarOrientation];
    if (orientation == UIInterfaceOrientationPortrait ||
        orientation == UIInterfaceOrientationPortraitUpsideDown)
    {
        animatedDistance = floor(PORTRAIT_KEYBOARD_HEIGHT * heightFraction);
    }
    else
    {
        animatedDistance = floor(LANDSCAPE_KEYBOARD_HEIGHT * heightFraction);
    }
    
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}


- (void)textFieldDidEndEditing:(UITextField *)textField
{
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
}
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range
 replacementText:(NSString *)text {
    
    // Any new character added is passed in as the "text" parameter
    
    if([text isEqualToString:@"\n"]) {
        
        // Be sure to test for equality using the "isEqualToString" message
        
        [textView resignFirstResponder];
        
        // Return FALSE so that the final '\n' character doesn't get added
        
        return NO;
    }
    
    // For any other character return TRUE so that the text gets added to the view
    
    return YES;
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
   // signup.enabled=YES;
    [textField resignFirstResponder];

    return YES;
}


TextView keyboard return


- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range 
replacementText:(NSString *)text {

    // Any new character added is passed in as the "text" parameter

    if([text isEqualToString:@"\n"]) {

        // Be sure to test for equality using the "isEqualToString" message

        [textView resignFirstResponder];

        // Return FALSE so that the final '\n' character doesn't get added

        return NO;
    }

    // For any other character return TRUE so that the text gets added to the view

    return YES;
}
//Connect textview delegate to the files owner.

Sunday, 25 November 2012

Loading a PDF in webview.


- (void)viewDidLoad
{
    [super viewDidLoad];
    NSString *path = [[NSBundle mainBundle] pathForResource:@"PP6" ofType:@"pdf"];
    NSURL *targetURL = [NSURL fileURLWithPath:path];
    NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
    [webView loadRequest:request];
}

In the webview Xib, Check "Scale pages to fit" if zooming required.

Friday, 6 July 2012

Creating Tabs on a view controller. and its Delegate

- (void)viewDidLoad {
    [super viewDidLoad];

UITabBar *m_tabbar;
if(m_tabbar)
        [m_tabbar removeFromSuperview];
   
    m_tabbar =  [[UITabBar alloc] initWithFrame:CGRectMake(0,422,320,40)];
    m_tabbar.backgroundColor = [UIColor redColor];
    [m_tabbar setDelegate:self];
    UITabBarItem* setttings = [[[UITabBarItem alloc] initWithTitle:@"Most Recent" image:[UIImage imageNamed:@"Settings.png"] tag:1]autorelease];
    UITabBarItem* mapbutton = [[[UITabBarItem alloc] initWithTitle:@"Community" image:[UIImage imageNamed:@"map.png"] tag:2]autorelease];
    UITabBarItem* nilbutton = [[[UITabBarItem alloc] initWithTitle:@"Settings" image:[UIImage imageNamed:@"locate.png"] tag:3]autorelease];
    NSArray* tabBarItems = [NSArray arrayWithObjects:setttings, nilbutton,mapbutton, nil];
    m_tabbar.items = tabBarItems;

self.view addSubview:m_tabbar];
    [m_tabbar setSelectedItem:[m_tabbar.items objectAtIndex:0]];

}


- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    switch (item.tag)
    {
        case 1:{
            Settings * setii=[[Settings alloc]init];
           [self.navigationController pushViewController:setii animated:YES];
            break;
        }
        case 2:
                    
            break;
           
           
        case 3:
        {
                       break;
        }   
        default:
            exit(0);
            break;
    }
}

Thursday, 5 July 2012

Navigating to a Tabbar Tab View


[self.tabBarController setSelectedIndex:1];

Adding a Line in Cell

UIView *lineView            = [[[UIView alloc] initWithFrame:CGRectMake(0, 68, 300, 1.5)] autorelease];
                lineView.backgroundColor    = [UIColor whiteColor];
                lineView.autoresizingMask   = 0x3f;
                [cell.contentView addSubview:lineView];

Round Corner imageView

imageView = [[UIImageView alloc] init];
    imageView.frame = CGRectMake(13.0f, 98.0f, 106.0f, 106.0f);
   
    CALayer * l = [imageView layer];
    [l setMasksToBounds:YES];
    [l setCornerRadius:8.0];
   
    [self.view addSubview:imageView];
   
     imageView.image = [UIImage imageNamed:@"imgee.png"];


//Add and Import  Quartscore frame work.

Adding BG Image to the cells

UIImage*    backgroundImage = nil;
    UIImageView* backgroundView    = [[UIImageView alloc] initWithFrame:cell.frame];
    if (indexPath.row == 0)
    {
        backgroundImage = [UIImage imageNamed:@"top_cell.png"];
       
    }
    else if (indexPath.row ==[xmlElementObjects count]-1)
    {
        backgroundImage    =[UIImage imageNamed:@"bottom_cell.png"];
    }
    else
    {
        backgroundImage    =[UIImage imageNamed:@"middle_cell.png"];
       
    }
    backgroundView.image = backgroundImage;
    [cell setBackgroundView:backgroundView];
   
    if (backgroundView)
    {
        [backgroundView release];
        backgroundView = nil;
    }

Wednesday, 18 April 2012

adding labels in cell programatically

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    //if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    //}
   
    // Configure the cell...
    //codee=[[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:7];
    //NSLog(@"FFF--%@",codee);
   
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 2.0, 170.0, 20.0)];
    lbl.font=[UIFont boldSystemFontOfSize:13.0];
    lbl.textColor = [UIColor blackColor];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.highlightedTextColor = [UIColor whiteColor];
    lbl.text = [[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:2];
    [cell.contentView addSubview:lbl];
   
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(170, 2.0, 120.0, 20.0)];
    lbl.font=[UIFont boldSystemFontOfSize:12.0];
    lbl.textAlignment = UITextAlignmentRight;
    lbl.textColor = [UIColor blackColor];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.highlightedTextColor = [UIColor whiteColor];
    lbl.text =[NSString stringWithFormat:@"%.2f %@", [[[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:4] doubleValue],[[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:5]];
    [cell.contentView addSubview:lbl];
   
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(5.0, 20.0, 228.0, 20.0)];
    lbl.font=[UIFont systemFontOfSize:10.0];
    lbl.textAlignment = UITextAlignmentLeft;
    lbl.textColor = [UIColor colorWithRed:57.0/255.0 green:122.0/255.0 blue:159.0/255.0 alpha:1.0];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.highlightedTextColor = [UIColor whiteColor];
    lbl.text =[NSString stringWithFormat:@"%@, %@", [[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:0],[[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:3]];
    [cell.contentView addSubview:lbl];
   
    lbl = [[UILabel alloc] initWithFrame:CGRectMake(230.0, 20.0, 60.0, 20.0)];
    lbl.font=[UIFont systemFontOfSize:10.0];
    lbl.textAlignment = UITextAlignmentRight;
    lbl.textColor = [UIColor grayColor];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.highlightedTextColor = [UIColor whiteColor];
    //lbl.text =[NSString stringWithFormat:@"%@", [[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:0]];
    [cell.contentView addSubview:lbl];
   
    NSArray *Arr1 = [[[ArrPOList objectAtIndex:indexPath.row] objectAtIndex:6] componentsSeparatedByString:@"-"];
    lbl.text = [NSString stringWithFormat:@"%@/%@/%@",[Arr1 objectAtIndex:2],[Arr1 objectAtIndex:1],[Arr1 objectAtIndex:0]];
   
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.backgroundColor=[UIColor clearColor];
    return cell;
}

Converting date formats and comparing

 NSString *newlyFormattedDateString,*newlyFormattedDateString1;
    if([[NSUserDefaults standardUserDefaults]objectForKey:@"datetoken"]){
        NSString *date1=[[NSUserDefaults standardUserDefaults]objectForKey:@"datetoken"];
   
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMM-dd-yyyy"];
        NSDate* datef = [dateFormatter dateFromString:date1];
       
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        newlyFormattedDateString = [dateFormatter stringFromDate:datef];
        [dateFormatter release], dateFormatter = nil;
        NSLog(@"datef-%@", newlyFormattedDateString);
       
      
    }
 
    if([[NSUserDefaults standardUserDefaults]objectForKey:@"tokenDate"]){
        NSString *date2=[[NSUserDefaults standardUserDefaults]objectForKey:@"tokenDate"];
    
        NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMM-dd-yyyy"];
        NSDate* datet = [dateFormatter dateFromString:date2];
       
        [dateFormatter setDateFormat:@"yyyy-MM-dd"];
        newlyFormattedDateString1 = [dateFormatter stringFromDate:datet];
        [dateFormatter release], dateFormatter = nil;
        NSLog(@"datet-%@", newlyFormattedDateString1);
       
    }
      
   
   
   
   
   
   
   
    //NSLog(@"Fromdate--%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"datetoken"]);
   //  NSDate * date1 = [[NSDate alloc] dateFromString:[[NSUserDefaults standardUserDefaults]objectForKey:@"datetoken"]];
    //NSLog(@"Todate--%@",[[NSUserDefaults standardUserDefaults]objectForKey:@"tokenDate"]);
   // NSDate * date2 = [[NSDate alloc] initWithString:[[NSUserDefaults standardUserDefaults]objectForKey:@"tokenDate"]];
   int j=0;
    NSComparisonResult result = [newlyFormattedDateString compare:newlyFormattedDateString1];
   
    switch (result)
    {
        case NSOrderedAscending: NSLog(@"%@ is in future from %@", newlyFormattedDateString1, newlyFormattedDateString); break;
        case NSOrderedDescending: NSLog(@"%@ is in past from %@", newlyFormattedDateString1, newlyFormattedDateString);
            j=1;
            break;
        case NSOrderedSame: NSLog(@"%@ is the same as %@", newlyFormattedDateString1, newlyFormattedDateString); break;
        default: NSLog(@"erorr dates %@, %@", newlyFormattedDateString1, newlyFormattedDateString); break;
    }

    if(j==1){
       
        UIAlertView *message = [[UIAlertView alloc] initWithTitle:@"Oops"
                                                          message:@"The 'To date' should be larger than 'From date'"
                                                         delegate:nil
                                                cancelButtonTitle:@"OK"
                                                otherButtonTitles:nil];
       
        [message show];
        [message  release];
    }else {

MailComposer (Email) in IOS

#import <MessageUI/MessageUI.h>
#import <MessageUI/MFMailComposeViewController.h>
// in .h of the view controller

//call 

-(void) sendMail{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            MFMailComposeViewController *controller = [[MFMailComposeViewController alloc] init];
            controller.mailComposeDelegate = self;
            //Subject of the mail
            NSString *sub = self.navigationItem.title;
            [controller setSubject:sub];
            NSArray *toRecipients = [NSArray arrayWithObject:[[ArrPOList objectAtIndex:0]objectAtIndex:6]];
            [controller setToRecipients:toRecipients];
            //Body of the mail
            //body = [NSString stringWithFormat:@"Wooow"];
            NSString *body=[[NSUserDefaults standardUserDefaults]objectForKey:@"Signature"];
            [controller setMessageBody:body isHTML:NO];
            [self presentModalViewController:controller animated:YES];
            [controller release];
           
        }
        else
            [self launchMailAppOnDevice];
    }
    else
        [self launchMailAppOnDevice];
}

- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Result: canceled");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Result: saved");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Result: sent");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Result: failed");
            break;
        default:
            NSLog(@"Result: not sent");
            break;
    }
    [self becomeFirstResponder];
    [self dismissModalViewControllerAnimated:YES];
   
}

-(void)launchMailAppOnDevice
{
    NSString *recipients = [[ArrPOList objectAtIndex:0]objectAtIndex:6];
    NSString *body=[[NSUserDefaults standardUserDefaults]objectForKey:@"Signature"];
//    NSUserDefaults *Defaults = [NSUserDefaults standardUserDefaults];
//    [Defaults setObject:body forKey:@"Signature"];
   
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];
   
   /* NSString *recipients = @"post@iratedphrase.com";
    NSString *body = data.text;
    NSString *email = [NSString stringWithFormat:@"%@%@", recipients, body];
    email = [email stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:email]];*/
}

Message composer code (SMS).


//

 MFMessageComposeViewController *picker = [[MFMessageComposeViewController alloc] init];
        if (picker == nil) {
            //[self ShowMsg"Message can be composed only in iPhone device."];
            return;
        }
        picker.messageComposeDelegate = self;
        picker.recipients = [NSArray arrayWithObject:telStr];
        [self presentModalViewController:picker animated:YES];
        [picker release];

Adding an image in Navigation bar in iOS5

Add the code just above the @implementation of rootview controller

@implementation UINavigationBar (CustomImage)
- (void)drawRect:(CGRect)rect {
    UIImage *image = [UIImage imageNamed:@"Header.png"];
    [image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
@end

@implementation RootViewController


//Paste the following code wherever you rerequire.

- (void)viewDidLoad {
    [super viewDidLoad];
      
    if ([self.navigationController.navigationBar respondsToSelector:@selector(setBackgroundImage:forBarMetrics:)] ) {
        UIImage *image = [UIImage imageNamed:@"Header.png"];
        [self.navigationController.navigationBar setBackgroundImage:image forBarMetrics:UIBarMetricsDefault];
    }
}

Tuesday, 20 March 2012

Adding "To Field" in ShareKit Email(Pre Setup)

In the button press.


NSString *someText = @"This is a blurb of text I highlighted from a document.";
SHKItem *item = [SHKItem text:someText];

[item setCustomValue:@"your@recipient.com" forKey:@"toField"];
// Share the item [SHKMail shareItem:item];



The add these lines in SHKMail.m in the method sendMail:
[mailController setSubject:item.title];
[mailController setMessageBody:body isHTML:YES];

// **start of added code
NSString *recipient = [item customValueForKey:@"toField"];
NSLog(@"recipient: %@", recipient);
if (recipient != nil) {
    NSArray *recipients = [[NSArray alloc] initWithObjects:recipient, nil];
    [mailController setToRecipients:recipients];
    [recipient release];
    [recipients release];
}
// **end of added code

[[SHK currentHelper] showViewController:mailController];


Email /Facebook /twitter only By Share-kit with a button press.

First import   #import "SHKMail.h" in the view Controller.


-(IBAction)Emailbutton:(id)sender{
    
    SHKItem *item;
     [SHK setRootViewController:self];
    NSURL *url = [NSURL URLWithString:@"sadiq"];
   item = [SHKItem URL:url title:@"Contact"];

    [SHKMail shareItem:item];

}

-(IBAction)FbButton:(id)sender{
 SHKItem *item;
     [SHK setRootViewController:self];
  NSURL *url = [NSURL URLWithString:@"http://www.google.com/"];
item = [SHKItem URL:url title:@"Google"];
[SHKFacebook shareItem:item];

}



Basic MapView Annotation Tuto

Monday, 19 March 2012

Executing a URL within the app.

NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://mma-in-nj.com/iphone/test/register_device.php?dt=%@",token]];
   NSLog(@"URL -- %@",url);
   
    NSMutableURLRequest *request1 = [[[NSMutableURLRequest alloc] init] autorelease];
    [request1 setURL:url];
    [request1 setHTTPMethod:@"GET"];
 
    [request1 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
    
   
    [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
   
    NSError *error;
    NSURLResponse *response;
    NSData *urlData=[NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
   
    NSString *data1=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSLog(@"here...%@",data1);  

Wednesday, 14 March 2012

Setting BackGround image and clearing the view

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.
    // Add the navigation controller's view to the window and display.
   
    UIView *backgroundView = [[UIView alloc] initWithFrame: _window.frame];
    backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"Bg.png"]];
    [_window addSubview:backgroundView];
   
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    return YES;
}

//wherever needed..


- (void)viewDidLoad
{
    [super viewDidLoad];
 
    self.view.backgroundColor=[UIColor clearColor];

}

Saturday, 10 March 2012

Deleting Tableview cell content and updating the content array stored by NSDocumentDirectory

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
       
        [amountSpend removeObjectAtIndex:indexPath.row];
       
        NSLog(@"after Delete-- %@",amountSpend);
       
       
        NSArray *path1 = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory1 = [path1 objectAtIndex:indexPath.row];
       
        NSString *fullFileName1 = [NSString stringWithFormat:@"%@amountSpend", documentsDirectory1];
        [amountSpend writeToFile:fullFileName1 atomically:NO];

       
       
        [tableView reloadData];
        // Delete the row from the data source
       // [tableView deleteRowsAtIndexPaths:[amountSpend indexOfObject:indexPath.row] withRowAnimation:UITableViewRowAnimationFade];
    }  
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }  
}

TableView Editing and Deleting code and Delegate

- (void)viewDidLoad
{
    [super viewDidLoad];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath

if (editingStyle == UITableViewCellEditingStyleDelete) {

 // Delete the row from the data source
       [tableView deleteRowsAtIndexPaths:[amountSpend indexOfObject:indexPath.row] withRowAnimation:UITableViewRowAnimationFade];
    }  
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }  
}

Friday, 2 March 2012

Trimming photo to a specific size with a php script.

NSString *str=[NSString stringWithFormat: @"http://iphone.jiujitsucoach.com/includes/timthumb.php?src=%@&h=150&w=150",[imageArray objectAtIndex:currentIndex_]];
   
    NSURL * imageURL = [NSURL URLWithString:str];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage * image = [UIImage imageWithData:imageData];

Retrieving multiple images saved in documents directory

- (void)viewDidLoad
{
   [super viewDidLoad];
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *fullFileName = [NSString stringWithFormat:@"%@imageArray", documentsDirectory];
    imageArray=[[NSMutableArray alloc]initWithContentsOfFile:fullFileName];
}

//where the image need to dispaly..

NSString *str=[NSString stringWithFormat: @"http://iphone.jiujitsucoach.com/includes/timthumb.php?src=%@&h=150&w=150",[imageArray objectAtIndex:currentIndex_]];
   
    NSURL * imageURL = [NSURL URLWithString:str];
    NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
    UIImage * image = [UIImage imageWithData:imageData];

Adding multiple images in to an array parsed from a server and saving it in the document directory.

- (void)viewDidLoad
{
   [super viewDidLoad];

 NSArray *paths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory,      NSUserDomainMask, YES);
 NSString *documentsDirectory = [paths objectAtIndex:0];
   NSString *fullFileName = [NSString stringWithFormat:@"%@imageArray", documentsDirectory];
   imageArray=[[NSMutableArray alloc]initWithContentsOfFile:fullFileName];

       if([imageArray count]==0){

           imageArray=[[NSMutableArray alloc]init];if(xmlElementObjects !=nil)
       {
           [xmlElementObjects release];
       }
       xmlElementObjects = [[NSMutableArray alloc] init];
     
    
     
     
       NSData *xml = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"http://iphone.jiujitsucoach.com/admin/gallery.php?action=generate"]];
       self.parser=[[NSXMLParser alloc]initWithData:xml];
       [self.parser setDelegate:self];
       [self.parser parse];
       [self.parser release];
       self.parser=nil;
     
           
       for(int i=0;i<[xmlElementObjects count];i++){
         
           eleme = [xmlElementObjects objectAtIndex:i];
                     [imageArray addObject:eleme.imageurl];
         
           [imageArray writeToFile:fullFileName atomically:NO];
      
         
       }
         
        NSLog(@"Not from Cache imageArry-- %@",imageArray);
       }
     
       else{
         
           NSLog(@"Hi from cache..");
           fullFileName = [NSString stringWithFormat:@"%@imageArray", documentsDirectory];
           imageArray=[[NSMutableArray alloc]initWithContentsOfFile:fullFileName];
           NSLog(@"imageArry-- %@",imageArray);

       }
}

Wednesday, 22 February 2012

Showing You Tube Video in a view.


//in .h , add 
- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame;




- (void)viewDidLoad
{
    [super viewDidLoad];
    [self embedYouTube:@"http://www.youtube.com/watch?v=fp14M7yQV-0" frame:CGRectMake(0, 44, 320, 200)];
    
}

- (void)embedYouTube:(NSString *)urlString frame:(CGRect)frame {
    NSString *embedHTML = @"\
    <html><head>\
    <style type=\"text/css\">\
    body {\
    background-color: transparent;\
    color: white;\
    }\
    </style>\
    </head><body style=\"margin:0\">\
    <embed id=\"yt\" src=\"%@\" type=\"application/x-shockwave-flash\" \
    width=\"%0.0f\" height=\"%0.0f\"></embed>\
    </body></html>";
    NSString *html = [NSString stringWithFormat:embedHTML, urlString, frame.size.width, frame.size.height];
    UIWebView *videoView = [[UIWebView alloc] initWithFrame:frame];
   // videoView.center = CGPointMake(200, 100 );
    
    [videoView loadHTMLString:html baseURL:nil];
    [self.view addSubview:videoView];
    [videoView release];
}


Tuesday, 21 February 2012

Adding data to a sever with the data and the URL seperately in the POST method.

NSString *post =[[NSString alloc] initWithFormat:@"account_type=%@&user_id=%@&user_name=%@&comment_text=%@&post_id=%@",type,[acct username],[acct accountDescription],item.text,commentID];
                       
                        NSURL *url=[NSURL URLWithString:@"http://iphone.jiujitsucoach.com/index.php?action=newcomment"];
                       
                        NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
                       
                        NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
                       
                        NSMutableURLRequest *request1 = [[[NSMutableURLRequest alloc] init] autorelease];
                        [request1 setURL:url];
                        [request1 setHTTPMethod:@"POST"];
                        [request1 setValue:postLength forHTTPHeaderField:@"Content-Length"];
                        [request1 setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
                        [request1 setHTTPBody:postData];
                       
                       
                        [NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
                       
                        NSError *error;
                        NSURLResponse *response;
                        NSData *urlData=[NSURLConnection sendSynchronousRequest:request1 returningResponse:&response error:&error];
                       
                        NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
                        NSLog(@"here...%@",data);

Adding Activity indicator programatically as sub view

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
     [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
   
    self.view.userInteractionEnabled=NO;
     UIActivityIndicatorView* indicator = [[UIActivityIndicatorView alloc] init];
    indicator.activityIndicatorViewStyle=UIActivityIndicatorViewStyleWhiteLarge;
    //indicator.color=  [UIColor  colorWithRed:0.655 green:0.729 blue:0.812 alpha:1.0];
    indicator.color=  [UIColor whiteColor];
    [indicator setFrame:CGRectMake(150, 170, 20, 20)];
    [self.view addSubview:indicator];
    [indicator startAnimating];
   
}

//Where the indicator needs to stop

[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
[indicator stopAnimating];

Direction from one location to another in Maps application

-(IBAction)directionButtonpress:(id)sender{

        NSString *destnlat=@"40.984042";
        NSString *destlong=@"-74.009993";
       
       // NSString *currentlat=[[NSUserDefaults standardUserDefaults]objectForKey:@"latitude"];
       // NSString *currentlong=[[NSUserDefaults standardUserDefaults]objectForKey:@"longitude"];
       
        NSString *currentlat=@"40.982435";
        NSString *currentlong=@"-74.016427";
       
        NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=%@,%@&daddr=%@,%@",currentlat,currentlong,destnlat,destlong];
       
        NSLog(@"%@",url);
       
        [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];

}

User Current Location Coordinates-iPhone

Add coreLocation frame work and then import
#import <CoreLocation/CoreLocation.h>     in the view the location cordinates is required.

//.h file

@interface HomeView : UIViewController<CLLocationManagerDelegate>{
  CLLocationManager *m_locationManager;
}

//.m file

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
   // [self.navigationController.navigationBar setAlpha:0.0];
   
    m_locationManager = [[CLLocationManager alloc] init];
    m_locationManager.delegate = self;
    m_locationManager.distanceFilter = kCLDistanceFilterNone;
    m_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    [m_locationManager startUpdatingLocation];
}


- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation
{   
    [manager stopUpdatingLocation];
    double lati = newLocation.coordinate.latitude+0.0;
    double longi = newLocation.coordinate.longitude+0.0;   
   
    NSNumber *lat = [NSNumber numberWithDouble:lati];
    NSNumber *lg = [NSNumber numberWithDouble:longi];
    NSLog(@"Current location-- %@-%@",lat,lg);
   
    [[NSUserDefaults standardUserDefaults] setObject:lat forKey:@"latitude"];
    [[NSUserDefaults standardUserDefaults] setObject:lg forKey:@"longitude"];
   
  }

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
   
    [manager stopUpdatingLocation];
       
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Device not Supported!" message:@""
                                                   delegate:self cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
   
    if(error != NULL)
        return;
}

Sunday, 29 January 2012

Returning to Parent View-iPhone

Dismiss ModalViewController-View Based

-(IBAction)btnClicked:(id)sender{
[self dismissModalViewControllerAnimated:YES];
}
 

Pop ViewController-Navigation Based

 

[self.navigationController popViewControllerAnimated:YES]; 

Popto RootViewController-Navigation Based

 

 [self.navigationController popToRootViewControllerAnimated:YES];

 

Thursday, 5 January 2012

Parsing the Below XML.

Make a NSObject class.
Add the following codes in the .h file

@interface XmlEle : NSObject {
    NSString *title;
    NSString *description;
    NSString *imageurl;
}
@property (nonatomic, retain) NSString *title,*description,*imageurl;
@end

//in .m

@implementation XmlEle
@synthesize title,description,imageurl;

-(void) dealloc{
    [title release];
    title=nil;
    [description release];
    description=nil;
    [imageurl release];
    imageurl=nil;
    [super dealloc];
    }
@end


//In View Controller .h

@interface RootViewController : UITableViewController {
    NSXMLParser *parser;
    NSMutableString *currentAttribute;
    NSMutableArray *xmlElementObjects;
    XmlEle *tempEle,*eleme;
    NSString *ggg;
    NSMutableArray *hhh;
}
@property (nonatomic, retain) NSXMLParser *parser;
@property (nonatomic, retain) NSMutableString *currentAttribute;
@property (nonatomic, retain) XmlEle *tempEle,*eleme;
@property (nonatomic, retain) NSMutableArray *xmlElementObjects;
@end

//in .m

@implementation RootViewController
@synthesize parser,currentAttribute, xmlElementObjects,tempEle,eleme;

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title=@"My Parser";
    hhh=[[NSMutableArray alloc]init];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
   
    if(xmlElementObjects !=nil)
    {
        [xmlElementObjects release];
    }
    xmlElementObjects = [[NSMutableArray alloc] init];
   
}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    NSData *xml = [NSData dataWithContentsOfURL: [NSURL URLWithString:@"file:///Users/sweans/Dropbox/iPhone/Xmls/MyxmlMOdi.xml"]];
    self.parser=[[NSXMLParser alloc]initWithData:xml];
    [self.parser setDelegate:self];
    [self.parser parse];
    [self.parser release];
    self.parser=nil;
   
    [self.tableView reloadData];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
   
}
- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    if(![elementName compare:@"item"])
    {
tempEle = [[XmlEle alloc] init];          
     }
    else if(![elementName compare:@"title"])
    {
        currentAttribute = [NSMutableString string];
    }
    else if(![elementName compare:@"description"])
    {
        currentAttribute = [NSMutableString string];
    }
    else if(![elementName compare:@"media:thumbnail"])
    {
        ggg =[attributeDict valueForKey:@"url"];
        [hhh addObject:ggg];
   }
}


- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
   
    if(![elementName compare:@"item"])
    {
        [xmlElementObjects addObject:tempEle];
        [tempEle release];
        tempEle=nil;
    }
   
    else if(![elementName compare:@"title"])
    {
        tempEle.title=currentAttribute;
        currentAttribute=nil;
    }
   
       
    else if(![elementName compare:@"description"])
    {
        tempEle.description=currentAttribute;
        currentAttribute=nil;
    }
   
}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if(currentAttribute){
    [self.currentAttribute appendString:string];}
   
}

//Where we want the data to be displayed!!Here in the table view cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    static NSString *CellIdentifier = @"Cell";
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
   
    // Configure the cell.
//cell.textLabel.text=@"Me";
   
    eleme = [xmlElementObjects objectAtIndex:indexPath.row];
    NSString *Title= [eleme.title stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" \n\t"]];
    NSString *Descree= [eleme.description stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@" \n\t"]];
   
    cell.textLabel.text=Title;
    cell.detailTextLabel.text=Descree;
       
   
   
       
        NSString* imageURL =[hhh objectAtIndex:indexPath.row];
        NSData* imageData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imageURL]];
        UIImage* imagee = [[UIImage alloc] initWithData:imageData];
        cell.imageView.image= imagee;
   
   
    return cell;
}


A Simple XML with a title,description and picture

<?xml version="1.0" encoding="UTF-8" ?>
<MyXML>

 <item>
<title>It takes just 6 milliseconds for a</title>
<description>It takes just 6 milliseconds for a frogfish to open his mouth and eat his prey.</description>
<media:thumbnail width="66" height="49" url="file:///Users/sweans/Desktop/Screenshot%202011-29-30%2012.29.19.png"/> 
</item>

<item>
<title>Its hihhaaaa</title>
<description>hgdfighfiuiohuoiiuighufdio and eat his prey.</description>
<media:thumbnail width="66" height="49" url="file:///Users/sweans/Desktop/Screenshot%202011-26-30%2012.26.40.png"/> 
</item>

<item>
<title>Iholallaaa</title>
<description>Ikjghjljldgjk ish to open his mouth and eat his prey.</description>
<media:thumbnail width="66" height="49" url="file:///Users/sweans/Desktop/SadiImage/Screenshot%202011-54-23%2013.54.04.png"/> 
</item>

</MyXML>
</rss>