Friday, 18 May 2012

how to consume webservice in iphone sdk

in .h file to define this////////////////////////

 NSMutableData *webData;
    NSMutableString *soapResults;
    NSURLConnection *conn;
    NSMutableArray *CategoryArray;
    NSMutableString *currentElementValue;
    IBOutlet UITableView *tblView;
    Category *aCategory;
    NSMutableDictionary *dictTemp;
    NSXMLParser *xmlParser;
    bool elementFound;



in .m file define this//////////////////////////

- (void)viewDidLoad
{
    [super viewDidLoad];
    tblView.delegate = self;
    tblView.dataSource = self;
   
    if(![CategoryArray count]>0 ){
        [self connectToWebService];
    }
    tblView.backgroundColor = [UIColor whiteColor];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [tblView setSeparatorColor:[UIColor grayColor]];

    // Do any additional setup after loading the view from its nib.
}


-(void)connectToWebService{
   
    // [NSThread detachNewThreadSelector:@selector(ShowActivity) toTarget:self withObject:nil];
   
    NSString *strUrl = [NSString stringWithFormat:@"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                        "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
                        "<soap:Body>"
                        "<GetNews xmlns=\"http://tempuri.org/\" />"
                        "</soap:Body>"
                        "</soap:Envelope>"];
   
    NSURL *url = [NSURL URLWithString:
                  @"http://tgm.ourappadmin.com/tgm.asmx"];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
   
    NSString *msgLength = [NSString stringWithFormat:@"%d",[strUrl length]];
    [req addValue:@"text/xml; charset=utf-8"
forHTTPHeaderField:@"Content-Type"];
    [req addValue:@"http://tempuri.org/GetNews"
forHTTPHeaderField:@"SOAPAction"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
   
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [strUrl dataUsingEncoding:NSUTF8StringEncoding]];
   
    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (conn) {
       
        webData = [[NSMutableData data] retain];
    }  
   
}

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    [webData setLength: 0];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [webData appendData:data];
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
   
    //[appDel.HUD hide:YES];
   
    UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Alert!!!" message:@"Make sure that you are connected to the Internet." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [av show];
    [av release];
    [connection release];
    [webData release];
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    if(xmlParser != nil && [xmlParser retainCount] > 0)
    {
        [xmlParser release]; xmlParser = nil;
    }
    xmlParser = [[NSXMLParser alloc] initWithData: webData];
    [xmlParser setDelegate: self];
    [xmlParser setShouldResolveExternalEntities: YES];
    // [appDel.HUD hide:YES];
    [xmlParser parse];
    [connection release];
    [webData release];
}

#pragma mark -
#pragma mark NSXMLParser methods
-(void)parser:(NSXMLParser*)parser
didStartElement:(NSString*)elementName
 namespaceURI:(NSString*)namespaceURI
qualifiedName:(NSString*)qualifiedName
   attributes:(NSDictionary*)attributeDict
{
    NSLog(@"element : %@",elementName);
   
    if([elementName isEqualToString:@"GetNewsResult"])
    {
       
        CategoryArray=[[NSMutableArray alloc]init];
       
    }
    else if([elementName isEqualToString:@"Pro_Master_ToolforMobile"])
    {
       
        if(dictTemp != nil && [dictTemp retainCount] > 0) {
           
            [dictTemp release];
            dictTemp = nil;
           
        }
        dictTemp = [[NSMutableDictionary alloc] init];
    }
}

-(void)parser:(NSXMLParser*)parser
foundCharacters:(NSString*)string
{
   
    if(!currentElementValue)
    {
        currentElementValue=[[NSMutableString alloc] initWithString:string];
    }
    else
    {
        [currentElementValue appendString:string];
    }
}
-(void)parser:(NSXMLParser*)parser
didEndElement:(NSString*)elementName
 namespaceURI:(NSString*)namespaceURI
qualifiedName:(NSString*)qualifiedName
{
    NSLog(@"%@",elementName);
    // if end of root element is found- i.e. end of your xml file.
    if ([elementName isEqualToString:@"a_id"] || [elementName isEqualToString:@"a_title"] || [elementName isEqualToString:@"a_desc"]) {
       
        [dictTemp setObject:currentElementValue forKey:elementName];
       
    }   
    else if([elementName isEqualToString:@"Pro_Master_ToolforMobile"])
    {
        [CategoryArray addObject:dictTemp];
        if(dictTemp != nil && [dictTemp retainCount] > 0)
        {
            [dictTemp release];
            dictTemp = nil;
        }
       
    }
    // [categoryTable reloadData];
    //[aCategory setValue:currentElementValue forKey:elementName];
   
    [currentElementValue release];
    currentElementValue=nil;
   
    NSLog(@"arr detail %@",CategoryArray);
}
- (void)parserDidEndDocument:(NSXMLParser *)parser{
   
    NSLog(@"Arr Detail : %@", CategoryArray);
    NSString *strPhone = [[NSString alloc] initWithFormat:@"%@",[[CategoryArray objectAtIndex:0] valueForKey:@"a_title"]];
    NSLog(@"%@",strPhone);
   
    if([CategoryArray count] > 0) {
       
        [tblView reloadData];
       
    }
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   
    return [CategoryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // UIImage *detailsButtonImage;
   
    static NSString *CellIdentifier = @"Cell";
   
   
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    cell.selectionStyle = NO;
    //   cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
   
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 8, 235, 20)];
    lbl.text = [[CategoryArray objectAtIndex:indexPath.row] valueForKey:@"a_title"];
    lbl.textAlignment = UITextAlignmentLeft;
    lbl.textColor = [UIColor redColor];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.font = [UIFont fontWithName:@"Verdana-Bold" size:13];
    lbl.numberOfLines=0;
    lbl.lineBreakMode = UILineBreakModeWordWrap;
    [cell addSubview:lbl];
    [lbl release];
   
   
    UILabel *lblDetail = [[UILabel alloc] initWithFrame:CGRectMake(5, 30, 165, 20)];
    lblDetail.text = [[CategoryArray objectAtIndex:indexPath.row] valueForKey:@"a_desc"];
    lblDetail.textAlignment = UITextAlignmentLeft;
    lblDetail.textColor = [UIColor grayColor];
    lblDetail.backgroundColor = [UIColor clearColor];
    lblDetail.font = [UIFont fontWithName:@"Verdana" size:10];
    lblDetail.numberOfLines=0;
    lblDetail.lineBreakMode = UILineBreakModeTailTruncation;
    [cell addSubview:lblDetail];
    [lblDetail release];
   
   
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 80;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *str = [[CategoryArray objectAtIndex:indexPath.row] valueForKey:@"a_desc"];
    NSString *strLabel = [[CategoryArray objectAtIndex:indexPath.row] valueForKey:@"a_title"];
    NewsDetail *newsDetail = [[NewsDetail alloc] initWithNibName:@"NewsDetail" bundle:nil];
    newsDetail.strPass=str;
    newsDetail.strLabel= strLabel;
    [self presentModalViewController:newsDetail animated:YES];
    [newsDetail release];
}

No comments:

Post a Comment