Wednesday 28 October 2015

How To Use Multiple Header Section in UItableView Ios/Iphone

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake

(0, 0, tableView.frame.size.width, 18)];
    /* Create custom view to display section header... */
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake

(10, 5, tableView.frame.size.width, 18)];
    [label setFont:[UIFont boldSystemFontOfSize:12]];
     NSString *string =[list objectAtIndex:section];
    /* Section header is in 0th index... */
    [label setText:string];
    [view addSubview:label];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0

green:177/255.0 blue:186/255.0 alpha:1.0]]; //your background color...
    return view;
}

Monday 26 October 2015

How To Use Xml In Ios


 - (void)viewDidLoad

   {
      NSURL *url = [[NSURL alloc]initWithString:@"yourURL"];
        NSXMLParser *parser = [[NSXMLParser alloc]initWithContentsOfURL:url];
        [parser setDelegate:self];
       BOOL result = [parser parse];
   }

    - (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)


        NSLog(@\"Did start element\");
    if ( [elementName isEqualToString:@"root"])
     {
        NSLog(@"found rootElement");
        return;
    }
    }

    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)

 elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
    {
        NSLog(@"Did end element");
        if ([elementName isEqualToString:@"root"])
            {
              NSLog(@"rootelement end");
            }

    }
    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
    {
        NSString *tagName = @"column";

       if([tagName isEqualToString:@"column"])
      {
           NSLog(@"Value %@",string);
      }

    }



down vote
   

This is how you can use NSXMLParser :

In your .h file declare :

NSMutableData       *webPortFolio;
NSMutableString     *soapResultsPortFolio;
NSURLConnection     *conn;

//---xml parsing---

NSXMLParser         *xmlParserPortFolio;
BOOL                elementFoundPortFolio;
NSMutableURLRequest *req;

NSString            *theXMLPortFolio;
NSString            *strSoapMsg;
UIAlertView         *alertView;











n your .m file use the following code:

-(void)callURL
{

     //Your logic to call URL.

     conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
     if (conn)
     {
         webPortFolio = [[NSMutableData data] retain];
     }
}
And to handle the response you can use following functions :

-(void)connection:(NSURLConnection *)connection

didReceiveResponse:(NSURLResponse *)response
{
    [webPortFolio setLength:0];    
}

-(void)connection:(NSURLConnection *)connection

didReceiveData:(NSData *)data
{
    [webPortFolio appendData:data];
}

-(void) connection:(NSURLConnection *) connection didFailWithError:(NSError *) error
{

    NSLog(@"error...................%@",[error description]);
    [webPortFolio release];
    [connection release];
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{

    //Check the request and returns the response.

    NSLog(@"DONE. Received Bytes: %d", [webPortFolio length]);

    theXMLPortFolio = [[NSString alloc]
                      initWithBytes: [webPortFolio mutableBytes]
                      length:[webPortFolio length]
                      encoding:NSUTF8StringEncoding];

    //---shows the XML---

    NSLog(@"shows the XML %@",theXMLPortFolio);
    [theXMLPortFolio release];   

    if(xmlParserPortFolio)
    {
        [xmlParserPortFolio release];
    }
    xmlParserPortFolio = [[NSXMLParser alloc] initWithData: webPortFolio];
    [xmlParserPortFolio setDelegate: self];
    [xmlParserPortFolio setShouldResolveExternalEntities:YES];
    [xmlParserPortFolio parse];
    [webPortFolio release];
    [connection release];
}

//---when the start of an element is found---
-(void)  parser:(NSXMLParser *) parser
didStartElement:(NSString *) elementName
   namespaceURI:(NSString *) namespaceURI
  qualifiedName:(NSString *) qName
     attributes:(NSDictionary *) attributeDict
{

    if( [elementName isEqualToString:@"your_tag_name"])
    {
        if (!soapResultsPortFolio)
        {
            soapResultsPortFolio = [[NSMutableString alloc] init];
        }
        elementFoundPortFolio = TRUE;
        NSLog(@"Registration...%@",soapResultsPortFolio);
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {
        elementFoundPortFolio = TRUE;
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {
        elementFoundPortFolio = TRUE;
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {
        elementFoundPortFolio = TRUE;
    }

}

-(void)parser:(NSXMLParser *) parser foundCharacters:(NSString *)string
{
    if (elementFoundPortFolio)
    {
        [soapResultsPortFolio appendString: string];
    }     
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(

 NSError *)parseError
{
    NSLog(@"Parser error %@ ",[parseError description]);
}


//---when the end of element is found---
-(void)parser:(NSXMLParser *)parser
didEndElement:(NSString *)elementName
 namespaceURI:(NSString *)namespaceURI
qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:@"your_tag_name"])
    {         
        NSLog(@"display the soap results%@",soapResultsPortFolio);
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {         
        //Perform required action
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {
        //Perform required action
    }
    else if([elementName isEqualToString:@"your_tag_name"])
    {
        //Perform required action
    }

    [soapResultsPortFolio setString:@""];
    elementFoundPortFolio = FALSE;
}

 

How To Set ScrollView Ios/Iphone

CGRect contentRect = CGRectZero;
for (UIView *view in self.scrollView.subviews) {
    contentRect = CGRectUnion(contentRect, view.frame);
}
self.scrollView.contentSize = contentRect.size;



(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    self.scrollView.contentSize = self.contentView.frame.size;
}

Thursday 22 October 2015

How to Use and access SOAP web services from ios.iphone

NSURL *sRequestURL = [NSURL URLWithString:@"http://w3schools.com/webservices/tempconvert.asmx"];
    NSMutableURLRequest *myRequest = [NSMutableURLRequest requestWithURL:sRequestURL];
    NSString *sMessageLength = [NSString stringWithFormat:@"%d", [sSOAPMessage length]];

    [myRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [myRequest addValue: @"http://www.w3schools.com/webservices/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];
    [myRequest addValue: sMessageLength forHTTPHeaderField:@"Content-Length"];
    [myRequest setHTTPMethod:@"POST"];
    [myRequest setHTTPBody: [sSOAPMessage dataUsingEncoding:NSUTF8StringEncoding]];

    NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:myRequest delegate:self];

    if( theConnection ) {
         self.webResponseData = [[NSMutableData data] retain];
    }else {
        NSLog(@"Some error occurred in Connection");

    }

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
     [self.webResponseData  setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
     [self.webResponseData  appendData:data];
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
     NSLog(@"Some error in your Connection. Please try again.");
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
     NSLog(@"Received Bytes from server: %d", [self.webResponseData length]);
     NSString *myXMLResponse = [[NSString alloc] initWithBytes: [self.webResponseData bytes] length:[self.webResponseData length] encoding:NSUTF8StringEncoding];
     NSLog(@"%@",myXMLResponse);
}

Wednesday 21 October 2015

How To Use MKAnotation Ios/Iphone

@implementation MapPin


@synthesize coordinate;

@synthesize title;

@synthesize subtitle;


- (id)initWithCoordinates:(CLLocationCoordinate2D)location


placeName:placeName description:description {

    self = [super init];

    if (self != nil) {

        coordinate = location;

        title = placeName;

        [title retain];

        subtitle = description;

        [subtitle retain];

    }

    return self;

}


- (void)dealloc {

    [title release];

    [subtitle release];

    [super dealloc];

}



@end

Set Dynamic UILable Size In Ios Iphone

CGSize maximumLabelSize = CGSizeMake(296,9999);

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font
                        constrainedToSize:maximumLabelSize
                        lineBreakMode:yourLabel.lineBreakMode];

//adjust the label the the new height.
CGRect newFrame = yourLabel.frame;
newFrame.size.height = expectedLabelSize.height;
yourLabel.frame = newFrame;

Tuesday 20 October 2015

How to use Section in Row Using UITableView in Ios/Iphone

@interface MapPin : NSObject<MKAnnotation> {
    CLLocationCoordinate2D coordinate;
    NSString *title;
    NSString *subtitle;
}

@property (nonatomic, readonly) CLLocationCoordinate2D coordinate;
@property (nonatomic, readonly) NSString *title;
@property (nonatomic, readonly) NSString *subtitle;

- (id)initWithCoordinates:(CLLocationCoordinate2D)location

placeName:(NSString *)placeName description:(NSString *)description;



pin = [[MapPin alloc] initWithCoordinates:[track startCoordinates]

placeName:@"Start" description:@""];
[map addAnnotation:pin];




- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:

(NSIndexPath *)indexPath
{

[self.tableView deselectRowAtIndexPath:indexPath animated:NO];

NSArray * nameArray = [self.sectionsArray objectAtIndex:indexPath.section];

PFUser *user = (PFUser*)[nameArray objectAtIndex:indexPath.row];

// PFUser *user = (PFUser*)[self.friends objectAtIndex:indexPath.section];

if (cell.accessoryType == UITableViewCellAccessoryNone)
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
    [self.recipients addObject:user.objectId];
NSLog(@"added:%@",user);
}
else {
    cell.accessoryType = UITableViewCellAccessoryNone;
    [self.recipients removeObject:user.objectId];
    NSLog(@"removed:%@",user);
}
// this is enough
}

Friday 16 October 2015

How To Use Button Text Property In Ios/iphone

[myButton setTitle:@"Play" forState:UIControlStateNormal];

[myButton setTitle:@"Play" forState:UIControlStateNormal];
[myButton setTitle:@"Stop" forState:UIControlStateSelected];

Wednesday 14 October 2015

How to Work Use of Radio Button In Ios/iphone

#import <UIKit/UIKit.h>

@interface RadioButton : UIButton

// Outlet collection of links to other buttons in the group.
@property (nonatomic, strong) IBOutletCollection(RadioButton)
 NSArray* groupButtons;

// Currently selected radio button in the group.
// If there are multiple buttons selected then it returns the first one.
@property (nonatomic, readonly) RadioButton* selectedButton;

selects second.
-(void) setSelected:(BOOL)selected;

// Find first radio with given tag and makes it selected.
// All of other buttons in the group become deselected.
-(void) setSelectedWithTag:(NSInteger)tag;

-(void) deselectAllButtons;

@end
===============================================================
#import "RadioButton.h"

@interface RadioButton()
{
    NSMutableArray* _sharedLinks;
}
@end

@implementation RadioButton

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        if(![[self allTargets] containsObject:self]) {
            [super addTarget:self action:@selector(onTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    return self;
}

-(void) awakeFromNib
{
    if(![[self allTargets] containsObject:self]) {
        [super addTarget:self action:@selector(onTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    }
}

-(void) addTarget:(id)target action:(SEL)action forControlEvents:
(UIControlEvents)controlEvents
{
    // 'self' should be the first target
    if(![[self allTargets] containsObject:self]) {
        [super addTarget:self action:@selector(onTouchUpInside) forControlEvents:UIControlEventTouchUpInside];
    }
    [super addTarget:target action:action forControlEvents:controlEvents];
}

-(void) onTouchUpInside
{
    [self setSelected:YES distinct:YES sendControlEvent:YES];
}

-(void) setGroupButtons:(NSArray *)buttons
{
    if(!_sharedLinks) {
        for(RadioButton* rb in buttons) {
            if(rb->_sharedLinks) {
                _sharedLinks = rb->_sharedLinks;
                break;
            }
        }
        if(!_sharedLinks) {
            _sharedLinks = [[NSMutableArray alloc] initWithCapacity:[buttons count]+1];
        }
    }

    BOOL (^btnExistsInList)(NSArray*, RadioButton*) = ^(NSArray* list, RadioButton* rb){
        for(NSValue* v in list) {
            if([v nonretainedObjectValue]==rb) {
                return YES;
            }
        }
        return NO;
    };

    if(!btnExistsInList(_sharedLinks, self)) {
        [_sharedLinks addObject:[NSValue valueWithNonretainedObject:self]];
    }

    for(RadioButton* rb in buttons) {
        if(rb->_sharedLinks!=_sharedLinks) {
            if(!rb->_sharedLinks) {
                rb->_sharedLinks = _sharedLinks;
            } else {
                for(NSValue* v in rb->_sharedLinks) {
                    RadioButton* vrb = [v nonretainedObjectValue];
                    if(!btnExistsInList(_sharedLinks, vrb)) {
                        [_sharedLinks addObject:v];
                        vrb->_sharedLinks = _sharedLinks;
                    }
                }
            }
        }
        if(!btnExistsInList(_sharedLinks, rb)) {
            [_sharedLinks addObject:[NSValue valueWithNonretainedObject:rb]];
        }
    }
}

-(NSArray*) groupButtons
{
    if([_sharedLinks count]) {
        NSMutableArray* buttons = [[NSMutableArray alloc] initWithCapacity:
[_sharedLinks count]];
        for(NSValue* v in _sharedLinks) {
            [buttons addObject:[v nonretainedObjectValue]];
        }
        return buttons;
    }
    return nil;
}

-(RadioButton*) selectedButton
{
    if([self isSelected]) {
        return self;
    } else {
        for(NSValue* v in _sharedLinks) {
            RadioButton* rb = [v nonretainedObjectValue];
            if([rb isSelected]) {
                return rb;
            }
        }
    }
    return nil;
}

-(void) setSelected:(BOOL)selected
{
    [self setSelected:selected distinct:YES sendControlEvent:NO];
}

-(void) setButtonSelected:(BOOL)selected sendControlEvent:(BOOL)sendControlEvent
{
    BOOL valueChanged = (self.selected != selected);
    [super setSelected:selected];
    if(valueChanged && sendControlEvent) {
        [self sendActionsForControlEvents:UIControlEventValueChanged];
    }
}

-(void) setSelected:(BOOL)selected distinct:(BOOL)distinct sendControlEvent:(BOOL)sendControlEvent
{
    [self setButtonSelected:selected sendControlEvent:sendControlEvent];

    if( distinct && (selected || [_sharedLinks count]==2) )
    {
        selected = !selected;
        for(NSValue* v in _sharedLinks) {
            RadioButton* rb = [v nonretainedObjectValue];
            if(rb!=self) {
                [rb setButtonSelected:selected sendControlEvent:sendControlEvent];
            }
        }
    }
}

-(void) deselectAllButtons
{
    for(NSValue* v in _sharedLinks) {
        RadioButton* rb = [v nonretainedObjectValue];
        [rb setButtonSelected:NO sendControlEvent:NO];
    }
}

-(void) setSelectedWithTag:(NSInteger)tag
{
    if(self.tag == tag) {
        [self setSelected:YES distinct:YES sendControlEvent:NO];
    } else {
        for(NSValue* v in _sharedLinks) {
            RadioButton* rb = [v nonretainedObjectValue];
            if(rb.tag == tag) {
                [rb setSelected:YES distinct:YES sendControlEvent:NO];
                break;
            }
        }
    }
}

- (void)dealloc
{
    for(NSValue* v in _sharedLinks) {
        if([v nonretainedObjectValue]==self) {
            [_sharedLinks removeObjectIdenticalTo:v];
            break;
        }
    }
}


@end







Tuesday 13 October 2015

How to Add Plus Button In TableView Cell Ios/iphone

UIButton *button = [UIButton buttonWithType:UIButtonTypeContactAdd];
[button setUserInteractionEnabled:NO];
cell.accessoryView = button;

Monday 12 October 2015

How To Work With CoreData Ios/Iphone

=> here work Core Data:-

#import <UIKit/UIKit.h>

@interface DeviceDetailViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UITextField *versionTextField;
@property (weak, nonatomic) IBOutlet UITextField *companyTextField;
@property (strong) NSManagedObject *device;
- (IBAction)cancel:(id)sender;
- (IBAction)save:(id)sender;

@end

#import "DeviceDetailViewController.h"

@interface DeviceDetailViewController ()

@end

@implementation DeviceDetailViewController
@synthesize device;

- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if (self.device) {
        [self.nameTextField setText:[self.device valueForKey:@"name"]];
        [self.versionTextField setText:[self.device valueForKey:@"version"]];
        [self.companyTextField setText:[self.device valueForKey:@"company"]];
    }

}

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

- (IBAction)cancel:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)save:(id)sender {
    NSManagedObjectContext *context = [self managedObjectContext];
   
    if (self.device) {
        // Update existing device
        [self.device setValue:self.nameTextField.text forKey:@"name"];
        [self.device setValue:self.versionTextField.text forKey:@"version"];
        [self.device setValue:self.companyTextField.text forKey:@"company"];

    } else {
        // Create a new device
        NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:@"Device" inManagedObjectContext:context];
        [newDevice setValue:self.nameTextField.text forKey:@"name"];
        [newDevice setValue:self.versionTextField.text forKey:@"version"];
        [newDevice setValue:self.companyTextField.text forKey:@"company"];
    }
   
    NSError *error = nil;
    // Save the object to persistent store
    if (![context save:&error]) {
        NSLog(@"Can't Save! %@ %@", error, [error localizedDescription]);
    }
   
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end

#import "DeviceViewController.h"
#import "DeviceDetailViewController.h"

@interface DeviceViewController ()
@property (strong) NSMutableArray *devices;
@end

@implementation DeviceViewController

- (NSManagedObjectContext *)managedObjectContext {
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;

    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
   
    // Fetch the devices from persistent data store
    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Device"];
    self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
   
    [self.tableView reloadData];
}

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

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    // Return the number of rows in the section.
    return self.devices.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
   
    // Configure the cell...
    NSManagedObject *device = [self.devices objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@ %@", [device valueForKey:@"name"], [device valueForKey:@"version"]]];
    [cell.detailTextLabel setText:[device valueForKey:@"company"]];
   
    return cell;
}


- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSManagedObjectContext *context = [self managedObjectContext];

    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete object from database
        [context deleteObject:[self.devices objectAtIndex:indexPath.row]];
       
        NSError *error = nil;
        if (![context save:&error]) {
            NSLog(@"Can't Delete! %@ %@", error, [error localizedDescription]);
            return;
        }
       
        // Remove device from table view
        [self.devices removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }
}

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] 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
    }  
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     */
}


#pragma mark - Segue

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"UpdateDevice"]) {
        NSManagedObject *selectedDevice = [self.devices objectAtIndex:[[self.tableView indexPathForSelectedRow] row]];
        DeviceDetailViewController *destViewController = segue.destinationViewController;
        destViewController.device = selectedDevice;
    }
}

@end


Sunday 11 October 2015

Work With Local Notification In Ios/iphone

=> Here Used One Class ViewController:-

=> NotifierViewController.h file looks like.
=> Also taken Method Action:-

@interface NotifierViewController : UIViewController&lt;UITableViewDelegate,UITableViewDataSource&gt; {
    IBOutlet UITableView *tableview;
    IBOutlet UIDatePicker *datePicker;
    IBOutlet UITextField *eventText;
}

@property (nonatomic, retain) IBOutlet UITableView *tableview;
@property (nonatomic, retain) IBOutlet UIDatePicker *datePicker;
@property (nonatomic, retain) IBOutlet UITextField *eventText;

- (IBAction) scheduleAlarm:(id) sender;

@end
==> Here used Implemention file :-

@implementation NotifierViewController

@synthesize datePicker,tableview, eventText;

- (IBAction) scheduleAlarm:(id) sender {

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
    datePicker = nil;
    tableview = nil;
    eventText = nil;
}

- (void)dealloc {
    [super dealloc];
}

@end
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // We only have one section
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of notifications
    return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];
}

- (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];
    }

    // Get list of local notifications
    NSArray *notificationArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    UILocalNotification *notif = [notificationArray objectAtIndex:indexPath.row];

    // Display notification info
    [cell.textLabel setText:notif.alertBody];
    [cell.detailTextLabel setText:[notif.fireDate description]];

    return cell;
}
=> Here Work With Sheduler Alerm :-

- (IBAction) scheduleAlarm:(id) sender {
    [eventText resignFirstResponder];

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    // Get the current date
    NSDate *pickerDate = [self.datePicker date];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit )
                                                   fromDate:pickerDate];
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit )
                                                   fromDate:pickerDate];
    // Set up the fire time
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];
    [dateComps setSecond:[timeComponents second]];
    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
        return;
    localNotif.fireDate = itemDate;
    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    // Notification details
    localNotif.alertBody = [eventText text];
    // Set the action button
    localNotif.alertAction = @"View";

    localNotif.soundName = UILocalNotificationDefaultSoundName;
    localNotif.applicationIconBadgeNumber = 1;

    // Specify custom data for the notification
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
    localNotif.userInfo = infoDict;

    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];

    [self.tableview reloadData];
}

=> App delegate .m file and Add the following code:-

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // Override point for customization after application launch.

    // Add the view controller's view to the window and display.
    [window addSubview:viewController.view];
    [window makeKeyAndVisible];

    application.applicationIconBadgeNumber = 0;

    // Handle launching from a notification
    UILocalNotification *localNotif =
    [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
    if (localNotif) {
        NSLog(@"Recieved Notification %@",localNotif);
    }

    return YES;
}

 - (void)application:(UIApplication *)app didReceiveLocalNotification:
   (UILocalNotification *)notif {
    // Handle the notificaton when the app is running
    NSLog(@"Recieved Notification %@",notif);
}

Friday 9 October 2015

Login Username And Password With Facebook for iOS/Iphone

==>  Working With login in ios 5 and ios 6 , Using  FBLoginView Class ,
    simplest way to login into facebook using Facebook sdk .

    FBLoginView * pFBLoginViewObj = [[FBLoginView alloc] init];
    [pFBLoginViewObj setFrame:self.view.frame];
    pFBLoginViewObj.delegate = self;//optional
    [self.view addSubview:pFBLoginViewObj];

How to Pass Data One ViewController to Another View Ios/Iphone

=> Here Taken One Example ViewControllerA and ViewControllerB

=>For Here Used pass a BOOL value from ViewControllerA to ViewControllerB:-.

    In ViewControllerB.h declared one property for the BOOL variable:

    @property(nonatomic) BOOL *isSomethingEnabled;

    In ViewControllerA you need to Say ViewControllerB so use It:-

    #import "ViewControllerB.h"

=>  Then where you want to load the view eg. didSelectRowAtIndex or some IBAction
    you need to set the property in ViewControllerB before you push it onto nav stack.

    ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
    viewControllerB.isSomethingEnabled = YES;
    [self pushViewController:viewControllerB animated:YES];

    This will set isSomethingEnabled in ViewControllerB to BOOL value YES.

==> Here Passing Data Forward Using The Segue's:-

==> If you are using Storyboards you are most likely using segues and
    will need this procedure to pass data forward. This is similar to the above but instead of passing
    the data before you push the view controller, you use a method called:-

=> Here Used One Of the Method Whitch is:-

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

==> Here Pass a BOOL from ViewControllerA to ViewControllerB:-

    In ViewControllerB.h create a property for the BOOL

    @property(nonatomic) BOOL *isSomethingEnabled;

    in ViewControllerA you need to tell it about ViewControllerB so use an

    #import "ViewControllerB.h"

=> Create a the segue from ViewControllerA to ViewControllerB on the storyboard and give it an identifier,
   in this example we'll call it "showDetailSegue"

=> Next we need to add the method to ViewControllerA that is called when any segue is performed,
   because of this we need to detect which segue was called and then do something.
   In our example we will check for "showDetailSegue"
   and if thats performed we will pass our BOOL value to ViewControllerB:-

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
        if([segue.identifier isEqualToString:@"showDetailSegue"]){
            ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
            controller.isSomethingEnabled = YES;
        }
    }

=>If you have your views embedded in a navigation controller you need to change the
   method above slightly to the following

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
        if([segue.identifier isEqualToString:@"showDetailSegue"]){
            UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
            ViewControllerB *controller = (ViewControllerB *)navController.topViewController;
            controller.isSomethingEnabled = YES;
        }
    }

=> This will set isSomethingEnabled in ViewControllerB to BOOL value YES.

==> Passing Data Back


    In ViewControllerB.h, below the #import, but above @interface you specify the protocol.

    @class ViewControllerB;

    @protocol ViewControllerBDelegate <NSObject>
 - (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
    @end

=> Next still in the ViewControllerB.h you need to setup a delegate property and
   synthesize in ViewControllerB.m

    @property (nonatomic, weak) id <ViewControllerBDelegate> delegate;

=> In ViewControllerB we call a message on the delegate when we pop the view controller.

    NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
    [self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];

=> That's it for ViewControllerB. Now in ViewControllerA.h, tell ViewControllerA to
   import ViewControllerB and conform to its protocol.

    #import "ViewControllerB.h"

    @interface ViewControllerA : UIViewController <ViewControllerBDelegate>
=>    In ViewControllerA.m implement the following method from our protocol

    - (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
    {
        NSLog(@"This was returned from ViewControllerB %@",item);
    }

=>  We need to tell ViewControllerB that ViewControllerA is its delegate before
    we push ViewControllerB on to nav stack:-

    ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
    viewControllerB.delegate = self
    [[self navigationController] pushViewController:viewControllerB animated:YES];

How to use Protocol In Ios/iphone

==> Here One Protocol Declared :
@protocol MyProtocol <NSObject>

=> Declared One Of the Method :-

  - (void)aRequiredMethod;

=> Here Required Method:
 @required
- (void)anotherRequiredMethod;

@optional
- (void)anOptionalMethod;

@end

@interface MyClass <MyProtocol>

@end

@property (nonatomic, weak) id<MyProtocol> delegate;

[self.delegate aRequiredMethod];

[self.delegate conformsToProtocol:@protocol(MyProtocol)]

[self.delegate respondsToSelector:@selector(anOptionalMethod)]

Thursday 8 October 2015

Use Category With Custom Method In Ios/Iphone

=> Here Seeing One Of the Imporetd Categortt Concept:=

#import <objc/runtime.h>

static void *MyClassResultKey;
@implementation MyClass

=> Here taken One method Of which Using Category In Ios:

 - (NSString *)test {

  NSString *result = objc_getAssociatedObject(self, &MyClassResultKey);
  if (result == nil)

{
    // do a lot of stuff
    result = ...;
    objc_setAssociatedObject(self, &MyClassResultKey,

                  result, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
  }
  return result;
}
=> finaly Object set Associate object Using Category:-

 @end

Wednesday 7 October 2015

How to Use Completion Block In Ios/iphone

=> Here Work with returnType (.h above @interface declaration)

=> typedef void (^CompleteDiceRolling)(NSInteger diceValue);

    Declared With One Of the a @property for the block (.h)

    @property (copy, nonatomic) CompleteDiceRolling completeDiceRolling;

    Declared here One Of a Method with finishBlock (.h)

    - (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))

     finishBlock;

=>  Use Periviose Method in .m file and commit finishBlock to @property
    declared before:-

    - (void)getDiceValueAfterSpin:(void (^)(NSInteger diceValue))

     finishBlock{
        self.completeDiceRolling = finishBlock;
    }

=>  Here Use completionBlock Pass Predefined variableType to it
    (Don't forget to check whether the completionBlock exists):-

    if( self.completeDiceRolling ){
        self.completeDiceRolling(self.dieValue);
    }

    => Finaly Use it With Work Completion Block.

Tuesday 6 October 2015

How to Set Row As per Cell Of UITableView Ios /Iphone

==> Here Used One of the UITbaleVIew Delegate and DataSourse file method:-

- (NSInteger)tableView:(UITableView *)tableView

 numberOfRowsInSection:(NSInteger)section {
return [[tmpArray objectAtIndex:section] count];
}

Monday 5 October 2015

Work With Payu Money In Ios/Iphone

=> Here Used One the Example Of the Payu Money Concept:-

    int i = arc4random() % 9999999999;
    NSString *strHash = [self createSHA512:[NSString

    stringWithFormat:@"%d%@",i,[NSDate date]]];

 // Generatehash512(rnd.ToString() + DateTime.Now);
    NSString *txnid1 = [strHash substringToIndex:20];
    NSLog(@"tnx1 id %@",txnid1);
    NSString *key = @"JBZaLc";
    NSString *amount = @"1000";
    NSString *productInfo = @"Nice product";
    NSString *firstname = @"Mani";
    NSString *email = @"mani.ingenius@gmail.com";
    NSString *phone = @"1234566";
    NSString *surl = @"www.google.com";
    NSString *furl = @"www.google.com";
    NSString *serviceprovider = @"payu_paisa";
    NSString *hashValue = [NSString stringWithFormat:

    @"%@|%@|%@|%@|%@|%@|||||||||||GQs7yium",key,txnid1,amount,

    productInfo,firstname,email];
    NSString *hash = [self createSHA512:hashValue];
    NSDictionary *parameters = [NSDictionary

    dictionaryWithObjects:[NSArray arrayWithObjects:txnid1,key,
    amount,productInfo,firstname,email,phone,surl,furl,hash,serviceprovider
    ,nil] forKeys:[NSArray arrayWithObjects:@"txnid",@"key",@"amount",

    @"productinfo",@"firstname",@"email",@"phone",@"surl",@"furl",@"hash",

    @"service_provider", nil]];
    __block NSString *post = @"";
    [parameters enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
        if ([post isEqualToString:@""]) {
            post = [NSString stringWithFormat:@"%@=%@",key,obj];
        }else{
            post = [NSString stringWithFormat:@"%@&%@=%@",post,key,obj];
        }

    }];
   NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
   allowLossyConversion:YES];
   NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)
   [postData length]];
   NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
   [request setURL:[NSURL URLWithString:[NSString stringWithFormat:

   @"https://test.payu.in/_payment"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded"

   forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];

    [_webviewSample loadRequest:request];

==> Here Used One Method Which is Encrypted SHA512 Password:-

-(NSString *)createSHA512:(NSString *)string
{
    const char *cstr = [string cStringUsingEncoding:NSUTF8StringEncoding];
    NSData *data = [NSData dataWithBytes:cstr length:string.length];
    uint8_t digest[CC_SHA512_DIGEST_LENGTH];
    CC_SHA512(data.bytes, (CC_LONG)data.length, digest);
    NSMutableString* output = [NSMutableString

    stringWithCapacity:CC_SHA512_DIGEST_LENGTH * 2];
    for(int i = 0; i < CC_SHA512_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02x", digest[i]];
    return output;
}

How To Work Lazy Loding With UITableView In Ios/Iphone

=> Here Used ForPayu Money Concept:-
=> How to Use It:-
#import "ViewController.h"

#import "UIImageView+WebCache.h"
@interface ViewController ()
{
NSArray *arrImagesUrl;
}
@end
@implementation ViewController


- (void)viewDidLoad{


[super viewDidLoad];
arrImagesUrl = [[NSArray alloc] initWithObjects:
@"http://static2.dmcdn.net/static/video/974/848/51848479:jpeg_preview_small.jpg?20121105222657",
@"http://static2.dmcdn.net/static/video/274/848/51848472:jpeg_preview_small.jpg?20121105222644",
@"http://static2.dmcdn.net/static/video/954/848/51848459:jpeg_preview_small.jpg?20121105222637",
@"http://static2.dmcdn.net/static/video/554/848/51848455:jpeg_preview_small.jpg?20121105222615",
@"http://static2.dmcdn.net/static/video/944/848/51848449:jpeg_preview_small.jpg?20121105222558",
@"http://static2.dmcdn.net/static/video/144/848/51848441:jpeg_preview_small.jpg?20121105222556",
@"http://static2.dmcdn.net/static/video/134/848/51848431:jpeg_preview_small.jpg?20121105222539",
@"http://static2.dmcdn.net/static/video/624/848/51848426:jpeg_preview_small.jpg?20121105222523",
@"http://static2.dmcdn.net/static/video/281/448/51844182:jpeg_preview_small.jpg?20121105222502",
@"http://static2.dmcdn.net/static/video/414/848/51848414:jpeg_preview_small.jpg?20121105222516",
@"http://static2.dmcdn.net/static/video/171/848/51848171:jpeg_preview_small.jpg?20121105223449",
@"http://static2.dmcdn.net/static/video/904/848/51848409:jpeg_preview_small.jpg?20121105222514",
@"http://static2.dmcdn.net/static/video/004/848/51848400:jpeg_preview_small.jpg?20121105222443",
@"http://static2.dmcdn.net/static/video/693/848/51848396:jpeg_preview_small.jpg?20121105222439",
@"http://static2.dmcdn.net/static/video/401/848/51848104:jpeg_preview_small.jpg?20121105222832",
@"http://static2.dmcdn.net/static/video/957/648/51846759:jpeg_preview_small.jpg?20121105223109",
@"http://static2.dmcdn.net/static/video/603/848/51848306:jpeg_preview_small.jpg?20121105222324",
@"http://static2.dmcdn.net/static/video/990/848/51848099:jpeg_preview_small.jpg?20121105222807", nil];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - TableView Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:
  (NSInteger)section
{
return arrImagesUrl.count;
}
- (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];
}
cell.textLabel.text = [NSString stringWithFormat:@"Image #%d", indexPath.row];
cell.imageView.contentMode = UIViewContentModeScaleAspectFill;
[cell.imageView setImageWithURL:[NSURL URLWithString:[arrImagesUrl objectAtIndex:indexPath.row]]

=> placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
 return cell;
}
@end
- (void)viewDidLoad
{
[superviewDidLoad];
arrImagesUrl = [[NSArrayalloc] initWithObjects:
@"http://static2.dmcdn.net/static/video/656/177/44771656:jpeg_preview_small.jpg?20120509154705",
@"http://static2.dmcdn.net/static/video/629/228/44822926:jpeg_preview_small.jpg?20120509181018",
@"http://static2.dmcdn.net/static/video/116/367/44763611:jpeg_preview_small.jpg?20120509101749",
@"http://static2.dmcdn.net/static/video/340/086/44680043:jpeg_preview_small.jpg?20120509180118",
@"http://static2.dmcdn.net/static/video/666/645/43546666:jpeg_preview_small.jpg?20120412153140",

nil];
}

Sunday 4 October 2015

How To Create Databse .DB Sqlite File In Ios/iphone

=> Hare Call the Method Of Whitch Declared Belove Side:

-(BOOL)application:(UIApplication *)application

 didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.

    [self createDb];

    return YES;
}
==> Create One Databse File And Create Db And Usingf Some Method:

 -(void)createDb
{
    NSArray *dir=NSSearchPathForDirectoriesInDomains

   (NSDocumentDirectory, NSUserDomainMask, YES);

    NSString *dbPath=[NSString

    stringWithFormat:@"%@/userDb.sqlite",[dir lastObject]];

    sqlite3 *db;

    NSFileManager *fm=[NSFileManager new];

    if([fm fileExistsAtPath:dbPath isDirectory:nil])
    {
        NSLog(@"Database already exists..");
        return;
    }

    if (sqlite3_open([dbPath UTF8String],&db)==SQLITE_OK)
    {
        const char *query="create table user

    (userName VARCHAR(20),userAdd VARCHAR(20), userPass VARCHAR(20))";

        if (sqlite3_exec(db, query, NULL, NULL, NULL)==SQLITE_OK)
        {
            NSLog(@"User table created successfully..");
        }else
        {
            NSLog(@"User table creation failed..");
        }

    }else
    {
        NSLog(@"Open table failed..");
    }
    sqlite3_close(db);
}

Saturday 3 October 2015

How To Use Animated ANd Hide Show UIView In Ios/Iphone

==> First Take Pne IBOutlet Of UIView And Then Use Animated:
==> How to Hide ANd Show Some Kind Of UIView In Ios:
import <UIKit/UIKit.h>

@interface ViewController: UIViewController
@property (strong, nonatomic) IBOutlet UIView *cautionView;


- (IBAction)btnToggleClick:(id)sender;
@property (strong, nonatomic) IBOutlet UIButton *btnToggle;
@end
.m file:

#import "ViewController.h"

@interface ViewController()
@end

@implementation ViewController

bool isShown = false;
- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
=> USe tHIS Action To toggle Click On Button:-
 - (IBAction)btnToggleClick:(id)sender {
    if (!isShown) {
        _cautionView.frame =  CGRectMake(130, 20, 0, 0);
        [UIView animateWithDuration:0.25 animations:^{
            _cautionView.frame =  CGRectMake(130, 30, 100, 200);
        }];
        isShown = true;
    } else {
        [UIView animateWithDuration:0.25 animations:^{
            _cautionView.frame =  CGRectMake(130, 30, 0, 0);
        }];
        isShown = false;
    }
}
=> Based ON Button Click Hide And Show And Make UIView Frmae Size On
   Button Clikced:-

Friday 2 October 2015

Use of Username And Pasword Post Method In Ios/Iphone

==> Here,  How can use of POST Method.: And Pass Parameter Username Password:

1. Use Some Like String With Actual Username And Password.

   NSString *post = [NSString stringWithFormat:@"Username=%@&Password=%@",
   @"username",@"password"];

2. PostString  That Encoding using NSASCIIStringEncoding  also

=> You Need Send That Post String To  NSData Format.


    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding
    allowLossyConversion:YES];


=> You need to send the actual length of your data. Calculate the length of
   the post string.

    NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]];

3. Use Object  a UrlRequest with  Properties Like HTTP Method,

=>  HTTP Header Field With Length of
    Post String. Create URLRequest object and initialize it.

    NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];

 =>   Set That URL Whitch going to Send The Data To That Request.

     [request setURL:[NSURL URLWithString:

     @"http://www.abcde.com/xyz/login.aspx"]];

 =>  Now, set HTTP method (POST or GET). Write this lines as it is in your code.

     [request setHTTPMethod:@"POST"];

 =>  Set HTTP header field with length of the post data.

    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];

 => Set Also Here Encoded Value For HTTP Header:-

   [request setValue:@"application/x-www-form-urlencoded"
   forHTTPHeaderField:@"Content-Type"];


=> Set UrlRequest with PostData To HttpBody:-

    [request setHTTPBody:postData];

 4. Create URLConnection object. Initialize it Using With The URLRequest.

   NSURLConnection *conn = [[NSURLConnection alloc]
   initWithRequest:request  delegate:self];

=> It returns the initialized URL connection , load the data for the URL request.
   You can check URL connection Based On Below Code  if/else statement as below.


    if(conn) {
    NSLog(@"Connection Successful");
    }  else {
    NSLog(@"Connection could not be made");
}
5.  To receive the data from the HTTP request , you can use the delegate

    methods provided by the URLConnection Class Reference.

    Delegate methods are as below.

=>// This method is used to receive the data which

   we get using post method.

- (void)connection:(NSURLConnection *)connection

didReceiveData:(NSData*)data

// This method receives the error report in case of connection is

not made to server.


- (void)connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error

// This method is used to process the data after connection

has made successfully.
- (void)connectionDidFinishLoading:(NSURLConnection *)connection

Post method to send request And Response In Ios /Iphone

 ==> Here Usd some IBOUTLET Of NSUrlCOnnection and
==> Used Some NsmutableData Object Using it Work it.

@property (retain, nonatomic) NSURLConnection *connection;
@property (retain, nonatomic) NSMutableData *receivedData;


==> Use this method to post some

-(void)postMethod
{
    [self.connection cancel];

    //initialize new mutable data

    NSMutableData *data = [[NSMutableData alloc] init];

    self.receivedData = data;

    //initialize url that is going to be fetched.

    NSURL *url = [NSURL URLWithString:@"http://192.168.0.176/idictionary/index.php?r=login"];

    //initialize a request from url

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[url standardizedURL]];

    //set http method

    [request setHTTPMethod:@"POST"];

==> Here  data whitch Using Post Data

    NSString *postData = @"mac_id=val2&email_id=abc@gmail.com&password=abcfggkjhkj";


==>Here You Heve to Give To Some Parameter Vakue That You Want:

    //set request content type we MUST set this value.

    [request setValue:@"application/x-www-form-urlencoded; charset=utf-8" forHTTPHeaderField:@"Content-Type"];

    //set post data of request

    [request setHTTPBody:[postData dataUsingEncoding:NSUTF8StringEncoding]];

    //initialize a connection from request

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    self.connection = connection;
    //start the connection

    [connection start];

}
==> Add Some Deleget file Of Method And Action Which Help it.

/*

=> this method might be calling more than one times according to incoming data size
 */

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{

    [self.receivedData appendData:data];
}
/*

 if there is an error occured, this method will be called by connection
 */

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"%@" , error);
}
/*

==>  if data is successfully received, this method will be called by connection

 */
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    //initialize convert the received data to string with UTF8 encoding

    NSString *htmlSTR = [[NSString alloc] initWithData:self.receivedData

                                              encoding:NSUTF8StringEncoding];

   // NSLog(@"%@" , htmlSTR);
    NSError *e = nil;
    NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: self.receivedData options:
    NSJSONReadingMutableContainers error: &e]; <== Here used One Parser Called   SBJson Prser

    NSLog(@"data %@",jsonArray);  <== here Some OutPut Display

    //show controller with navigation
}

Push viewController from code and storyboard In Ios

PlaceViewController *newView = 
 [self.storyboard instantiateViewControllerWithIdentifier:
@"storyBoardIdentifier"];
[self.navigationController pushViewController:newView animated:YES];
 
 
 
 

For Storyboards, you should use performSegueWithIdentifier like so: 
[self performSegueWithIdentifier:@"identifier goes here" sender:self];
 

Thursday 1 October 2015

How To Work With UIActionsheet Using Diffrent ButtonIndex In Ios/Iphone

==> Here Use Some UIActionSheet Confrim Delegates file And Use it.
=> Take One Object Of It.
=> Create One VIewCOntrollwr Of Use UIACtionSheet And Its Delegate FIle AMthods:

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.webView.delegate = self;
    self.title = @"Apple";
    [self loadRequestFromString:@"http://www.apple.com"];
    // Do any additional setup after loading the view, typically from a nib.
}

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

==>Declared and Used Implemented UIAction Of Button And It Pass Sender Paremater:

- (IBAction)btnMoreClick:(id)sender{
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Choose your site" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Google" otherButtonTitles:@"Yahoo",@"Facebook",@"Twitter",@"HTML File",nil];
   
    actionSheet.actionSheetStyle = UIActionSheetStyleDefault;
   
    [actionSheet showInView:self.view];

}

=> This Method Used For Load Request URL From Some String Link and Load in UIWebView:

- (void)loadRequestFromString:(NSString*)urlString
{
    NSURL *url = [NSURL URLWithString:urlString];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:urlRequest];
}
=> Declared Some UI  updated Button Whre Use Using Go FOrwrd , Go backword Reload , Refresh

#pragma mark - Updating the UI
- (void)updateButtons
{
//    NSLog(@"%s loading = %@", __PRETTY_FUNCTION__, self.webView.loading ? @"YES" : @"NO");
    self.forward.enabled = self.webView.canGoForward;
    self.back.enabled = self.webView.canGoBack;
    self.stop.enabled = self.webView.loading;
}
==> Here Implmemted Some Delgate Method And Action Of UIwebView :

#pragma mark - UIWebViewDelegate
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return YES;
}

- (void)webViewDidStartLoad:(UIWebView *)webView
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    [self updateButtons];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
    NSLog(@"%s", __PRETTY_FUNCTION__);
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self updateButtons];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self updateButtons];
}
=> Now Here Implemented Some Delegate UIActionSheet:

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"%d",buttonIndex);
    if (buttonIndex==0) {
       [self loadRequestFromString:@"http://www.google.com"];
        self.title = @"Google";
    }else if (buttonIndex==1){
        [self loadRequestFromString:@"http://www.yahoo.com"];
        self.title = @"Yahoo";
    }else if (buttonIndex==2){
        [self loadRequestFromString:@"http://www.facebook.com"];
        self.title = @"Facebook";
    }else if (buttonIndex==3){
        [self loadRequestFromString:@"http://www.twitter.com"];
        self.title = @"Twitter";
    }else if (buttonIndex==4){
        self.title = @"HTML File";
//        NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"termsCond" ofType:@"htm"];
//        NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
//        [self.webView loadHTMLString:htmlString baseURL:nil];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"termsCond" ofType:@"html"];
        NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
        NSURLRequest *req = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:req];
    }
   
}

How To Work With UITableView Delegate method CommitEditingStyle In Ios/Iphone


=> Here Used One Delegate Method Of UITableView :

=> when Use Swipe Delete adn Swipe Insert Swift None :
=> on Swipe Action Its Work on UITableView Delegae EditeCommiteStyle Like This:

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0)
    {
        return UITableViewCellEditingStyleInsert;
    }
    else if(indexPath.row == 1)
    {
        return UITableViewCellEditingStyleDelete;
    }
   
    return UITableViewCellEditingStyleNone;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        NSLog(@"Delete action performed for row - %lu", indexPath.row);
    }
    else if(editingStyle == UITableViewCellEditingStyleInsert)
    {
        NSLog(@"Insert action performed for row - %lu", indexPath.row);
    }
}

How To Use Resource File Like Html In Ios/Iphone


=> Here Some Use To How to Take Html Path Resources Of NS Main Bunddle:
=> Here Load ANd Use HTML Fole From Bunddle Resourses:
=> Take Forst NSSting Object :
=> Using That Path It Using UTF8StringEncoding Mthod :
=> it Adding PresentageEscapeUsing UIWebVIew Adan Display contect Of HTML:

NSString *htmlFile = [[NSBundle mainBundle] pathForResource:@"termsCond" ofType:@"htm"];
//        NSString* htmlString = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
//        [self.webView loadHTMLString:htmlString baseURL:nil];
        NSString *path = [[NSBundle mainBundle] pathForResource:@"termsCond" ofType:@"html"];
        NSURL *url = [NSURL URLWithString:[path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

How To Work Social Sharing Facebook And Twiter in Ios /Iphone

==>First To For Sharing :
==> This Code Ss Usefull For Sharing your Contant On Facebook Twiter:
.

=>This code write in SocialShare.h file.

=> Social Sharing Imporeted Some Framwork Like Social And Accounts :

#import <Foundation/Foundation.h>
#import <Social/Social.h>
#import <Accounts/Accounts.h>
@interface SocialShare : NSObject
{
   
}

+ (id) instantiateSociaShare;
- (void)shareWithTwitter:(NSMutableDictionary *)dictShareInfo withViewController:(UIViewController *)viewController;
- (void)shareWithFacebook:(NSMutableDictionary *)dictShareInfo withViewController:(UIViewController *)viewController;

@end
-------------------------------------------------------
==>This code will be write in SocialShare.m file.

#import "SocialShare.h"

@implementation SocialShare

==> Cretaed Instances Singlton Object Of Social Shares:

+ (id) instantiateSociaShare
{
    static SocialShare *singletonInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if(!singletonInstance) {
            singletonInstance = [[SocialShare alloc] init];
        }
    });
    return singletonInstance;
}

=> Now This Method Usiing For Share With Twitter:

- (void)shareWithTwitter:(NSMutableDictionary *)dictShareInfo withViewController:(UIViewController *)viewController
{
   
       
        if([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
        {
            dispatch_async(dispatch_queue_create("Twitter", NULL), ^{
               
                SLComposeViewController *aSLCVCTwitter = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
                SLComposeViewControllerCompletionHandler completionBlock = ^(SLComposeViewControllerResult result) {
                    if (result == SLComposeViewControllerResultDone)
                    {
                        [[[UIAlertView alloc]initWithTitle:@"Your app name." message:@"Shared on twitter successfully." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
                    }
                    else
                    {
                        //[[[UIAlertView alloc]initWithTitle:kAppTitle message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
                    }
                    [aSLCVCTwitter dismissViewControllerAnimated:YES completion:Nil];
                };
               
                aSLCVCTwitter.completionHandler = completionBlock;
                [aSLCVCTwitter setInitialText:[dictShareInfo objectForKey:@"textToShare"]];
                if([dictShareInfo objectForKey:@"imageFromURLToShare"])
                {
                    UIImage *aImgToShare = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dictShareInfo objectForKey:@"imageFromURLToShare"]]]];
                    if(aImgToShare)
                    {
                        [aSLCVCTwitter addImage:aImgToShare];
                    }
                }
               
                [viewController presentViewController:aSLCVCTwitter animated:YES completion:^{
                   
                }];
            });
        }
        else
        {
          
            UIAlertView *aUIAlert = [[UIAlertView alloc]initWithTitle:@"App name" message:@"Your twitter account is not configured. Please configure it from your iphone's settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [aUIAlert show];
        }
   
}
=> Share With Facebook In Social Sharing:

- (void)shareWithFacebook:(NSMutableDictionary *)dictShareInfo withViewController:(UIViewController *)viewController
{

      
       
        if([SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook])
        {
            dispatch_async(dispatch_queue_create("Facebook", NULL), ^{
               
                SLComposeViewController *aSLCVCFacebook = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeFacebook];
                SLComposeViewControllerCompletionHandler completionBlock = ^(SLComposeViewControllerResult result) {
                    if (result == SLComposeViewControllerResultDone)
                    {
                        [[[UIAlertView alloc]initWithTitle:@"Your app name" message:@"Shared on facebook successfully." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
                    }
                    else
                    {
                        // [[[UIAlertView alloc]initWithTitle:kAppTitle message:@"" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]show];
                    }
                    [aSLCVCFacebook dismissViewControllerAnimated:YES completion:Nil];
                };
               
                aSLCVCFacebook.completionHandler = completionBlock;
                [aSLCVCFacebook setInitialText:[dictShareInfo objectForKey:@"textToShare"]];
                if([dictShareInfo objectForKey:@"imageFromURLToShare"])
                {
                    UIImage *aImgToShare = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[dictShareInfo objectForKey:@"imageFromURLToShare"]]]];
                    if(aImgToShare)
                    {
                        [aSLCVCFacebook addImage:aImgToShare];
                    }
                }
               
                [viewController presentViewController:aSLCVCFacebook animated:YES completion:^{
                   
                }];
            });
        }
        else
        {
==> Relaeted Sharing Its Display UIAlertVIew:
           
            UIAlertView *aUIAlert = [[UIAlertView alloc]initWithTitle:@"Your app name" message:@"Your facebook account is not configured. Please configure it from your iphone's settings." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [aUIAlert show];
        }
 
}

@end
-----------------------
=?This code will be written in ViewController.h file.
=> Now Create One ViewController:


#import <UIKit/UIKit.h>
#import "SocialShare.h"
#import <Accounts/Accounts.h>
#import <Social/Social.h>
@interface ViewController : UIViewController
{
    __weak IBOutlet UILabel *lblName;
    ACAccountStore *accountStore;
    __weak IBOutlet UILabel *lblEmail;
    __weak IBOutlet UIImageView *imgVwProfilePic;
    __weak IBOutlet UIImageView *imgVwCoverPic;
}
- (IBAction)btnFacebookAction:(id)sender;
- (IBAction)btnGetTimelineAction:(id)sender;
- (IBAction)btnTwitterAction:(id)sender;

@end
----------------------------------------------

=>This code will be written in ViewController.m file.
 
#import "ViewController.h"
#import "SocialShare.h"
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    accountStore = [[ACAccountStore alloc]init];
    // Do any additional setup after loading the view, typically from a nib.
}

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

- (IBAction)btnFacebookAction:(id)sender {
    NSMutableDictionary *aDict = [NSMutableDictionary dictionary];
    [aDict setObject:@"This is a test post!!!" forKey:@"textToShare"];
    [aDict setObject:@"http://www.indianic.com/newsite_v5/wp-content/themes/indianic/images/enterprise/indianic-footer-symbole.png" forKey:@"imageFromURLToShare"];
    [[SocialShare instantiateSociaShare] shareWithFacebook:aDict withViewController:self];
   
}
- (IBAction)btnGetTimelineAction:(id)sender {
 
    ACAccountType *aAccountType=[accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
   

    NSDictionary *dictOfId=[NSDictionary dictionaryWithObjectsAndKeys:@"354921344713153",ACFacebookAppIdKey,ACFacebookAudienceOnlyMe,ACFacebookAudienceKey,@[@"email"],ACFacebookPermissionsKey, nil];
    [accountStore requestAccessToAccountsWithType:aAccountType options:dictOfId completion:^(BOOL granted, NSError *error) {
       
        if (granted) {
            ACAccount *account=[[accountStore accountsWithAccountType:aAccountType] lastObject];
            ACAccountCredential *fbCredential = [account credential];
            NSString *accessToken = [fbCredential oauthToken];
            // profile details
            NSString *urlString = [NSString
                                   stringWithFormat:@"https://graph.facebook.com/me?fields=id,name,email,first_name,last_name,cover,picture{url}&access_token=%@",
                                   [accessToken stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
            urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
            NSURL *url = [NSURL URLWithString:urlString];
            NSDictionary *aDictFbResponse=[NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfURL:url] options:NSJSONReadingMutableLeaves error:nil];
           
            NSString *strEmail=[aDictFbResponse objectForKey:@"email"];
//            NSString*  strFbId=[aDictFbResponse objectForKey:@"id"];
            lblEmail.text = strEmail;
            lblName.text = [aDictFbResponse objectForKey:@"name"];
            imgVwCoverPic.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[aDictFbResponse objectForKey:@"cover"] objectForKey:@"source"]]]];
            imgVwProfilePic.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[[[aDictFbResponse objectForKey:@"picture"] objectForKey:@"data"] objectForKey:@"url"]]]];

            
           
        }
    }];
}

- (IBAction)btnTwitterAction:(id)sender {
    NSMutableDictionary *aDict = [NSMutableDictionary dictionary];
    [aDict setObject:@"This is a test post!!!" forKey:@"textToShare"];
    [aDict setObject:@"http://www.indianic.com/newsite_v5/wp-content/themes/indianic/images/enterprise/indianic-footer-symbole.png" forKey:@"imageFromURLToShare"];
    [[SocialShare instantiateSociaShare] shareWithTwitter:aDict withViewController:self];
}
@end