Wednesday, June 19, 2013

Soap webservice call


this is url :- http://www.w3schools.com/webservices/tempconvert.asmx?op=CelsiusToFahrenheit

download TouchXml freamwork

then #import "TouchXML.h"

///////////////////////////////////////////////////////     in your .h file  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

@interface RootViewController : UIViewController {
          NSString *strBarcodeid;
           NSMutableData *webData;
           NSXMLParser *xmlParser;
           NSString *element;
}


-(IBAction)onParse:(id)sender;


///////////////////////////////////////////////////////     in your .m file  \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

-(IBAction)onClickParse:(id)sender{
    NSString *soapMessage = [NSString stringWithFormat:
                             @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"
                             "<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/\">\n"
                             "<soap:Body>\n"
                             "<CelsiusToFahrenheit xmlns=\"http://tempuri.org/\">\n"    //hear action pass check 
                             "<Celsius>100</Celsius>\n"//HERE PARAMETER PASS  
                             "</CelsiusToFahrenheit>\n"   //hear action pass check in link
                             "</soap:Body>\n"
                             "</soap:Envelope>\n"
                             ];
    NSLog(@"%@",soapMessage);
NSURL *url = [NSURL URLWithString:@"http://www.w3schools.com/webservices/tempconvert.asmx"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
NSString *msgLength = [NSString stringWithFormat:@"%d", [soapMessage length]];
[theRequest addValue: @"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
[theRequest addValue: @"http://tempuri.org/CelsiusToFahrenheit" forHTTPHeaderField:@"SOAPAction"];      //hear action pass
[theRequest addValue: msgLength forHTTPHeaderField:@"Content-Length"];
[theRequest setHTTPMethod:@"POST"];
[theRequest setHTTPBody: [soapMessage dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(@"theConnection is NULL");
}
}


///////////connection delegate method for responce---------

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
webData = [[NSMutableData data] retain];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[webData appendData:data];
NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>");
}

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

NSLog(@"ERROR with theConenction %@",error);
UIAlertView *connectionAlert = [[UIAlertView alloc] initWithTitle:@"Information !" message:@"Internet / Service Connection Error" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[connectionAlert show];
[connectionAlert release];
[connection release];
[webData release];
return;
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
NSString *theXML = [[NSString alloc] initWithBytes: [webData mutableBytes] length:[webData length] encoding:NSUTF8StringEncoding];
    theXML = [theXML stringByReplacingOccurrencesOfString:@"&gt;" withString:@">"];
    theXML = [theXML stringByReplacingOccurrencesOfString:@"&lt;" withString:@"<"];
NSLog(@"Received data :%@",theXML);

/* CXMLDocument *doc = [[[CXMLDocument alloc] initWithData:webData options:0 error:nil] autorelease];
NSArray *nodes1 = [doc nodesForXPath:@"//return" error:nil];
NSLog(@"node counts : %d", [nodes1 count]);
for (CXMLElement *node in nodes1) {
for(int counter = 0; counter < [node childCount]; counter++) {    
if ([[[node childAtIndex:counter] name] isEqualToString:@"username"]) {
NSString *str = [[node childAtIndex:counter] stringValue];
NSLog(@"=====================>>string for username : %@\n", str);
}
}
}*/

[connection release];
    [webData release];

}



Json Parsing Example


Steps

first Add "ASSIHTTP" and "JSON" to your project




add all this framework to your project

in your .h file import and set delegate 

#import "HttpWrapper.h"  //import class then add delegete of this
@interface ViewController : UIViewController<HttpWrapperDelegate>
{
}@end


in your .m file call the webservice
-(void)loadWebseviceData
{
 HttpWrapper *httpWrapper=[[HttpWrapper alloc]initWithDelegate:self]; // create object of class with deleget method
    NSMutableDictionary *dicPass=[[NSMutableDictionary alloc]init]; // create a dictionary for a send parameter
    [dicPass setValue:@"Appointments" forKey:@"action"];   //pass action to webseriver
    [dicPass setValue:appDelegate.userId forKey:@"id"];   // pass parameter
    [httpWrapper requestWithMethod:@"POST" url:WEB_URL param:dicPass selSuc:@selector(fetchDataSuccessForClient:) selFail:@selector(fetchDataFail:)];   // fetch data 
}


// if fetch data sucess then call this
-(void)fetchDataSuccessForClient:(NSMutableDictionary *)response
{

 NSLog(@"%@",response);
}


// if fetch data fail then then call this
-(void)fetchDataFail:(NSError *)error
{

}

HttpWrapper.h

@class ASIFormDataRequest;

@protocol HttpWrapperDelegate

@optional
- (void) fetchDataSuccess:(NSString *)response;
- (void) fetchDataFail:(NSError *)error;
- (void) fetchImageSuccess:(NSString *)response;
- (void) fetchImageFail:(NSError *)error;

@end


@interface HttpWrapper : NSObject {
    
   NSObject<HttpWrapperDelegate> *delegate;
        
    SEL fetchSuccess;
SEL fetchFail;
}

@property SEL fetchSuccess;
@property SEL fetchFail;

@property (nonatomic, assign) NSObject<HttpWrapperDelegate> *delegate;

-(id)initWithDelegate:(id)del;

-(void) requestWithMethod:(NSString*)method url:(NSString*)strUrl param:(NSMutableDictionary*)dictParam selSuc:(SEL)forSuc selFail:(SEL)forFail;


@end


HttpWrapper.m

#import "HttpWrapper.h"
#import "ASIFormDataRequest.h"
#import "NSObject+SBJSON.h"
#import "SBJSON.h"

@implementation HttpWrapper

@synthesize delegate, fetchSuccess, fetchFail;

-(id)initWithDelegate:(id)del {
    self = [super init];
    if(self) {
        delegate = del;
    }
    return self;
}

-(void) requestWithMethod:(NSString*)method url:(NSString*)strUrl param:(NSMutableDictionary*)dictParam selSuc:(SEL)forSuc selFail:(SEL)forFail
{
    fetchSuccess = forSuc;
    
    fetchFail = forFail;
    
    NSLog(@"HttpWrapper method:%@ >> %@ ", method, strUrl);
    NSLog(@"%@",dictParam);
    
    NSURL *url = [NSURL URLWithString:strUrl];
    ASIFormDataRequest *requestMain = [ASIFormDataRequest requestWithURL:url];
    
    [requestMain setRequestMethod:method];
    
    if(dictParam != nil) {
        NSArray *allKey = [dictParam allKeys];
        for(int i=0; i<[allKey count]; i++) {
            NSString *key = [allKey objectAtIndex:i];            
            
            if([key isEqualToString:@"file"]) {
                NSMutableDictionary *dict = [dictParam valueForKey:key];
                NSString *filepath = [dict valueForKey:@"filepath"];
                NSString *filekey = [dict valueForKey:@"filekey"];
                [requestMain setFile:filepath forKey:filekey];
            } else {
                
                NSString *value = [dictParam valueForKey:key];
                [requestMain setPostValue:value forKey:key];
            }
        }
    }
    [requestMain setDelegate:self];
    [requestMain startAsynchronous];
    
}

- (void)requestFinished:(ASIHTTPRequest *)request {
    
    NSString *responseString = [request responseString];
    NSLog(@"HttpWrapper > requestFinished > %@",responseString);

    SBJSON *parser = [[[SBJSON alloc] init] autorelease];
    NSDictionary *dic = (NSDictionary *)[parser objectWithString:responseString error:nil];
    
    if([delegate respondsToSelector:fetchSuccess])
        [delegate performSelector:fetchSuccess withObject:dic];
    
    
    request = nil;
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"HttpWrapper > requestFailed > error: %@",error);
    
    request = nil;
    
    if([delegate respondsToSelector:fetchFail])
        [delegate performSelector:fetchFail withObject:error];
}

@end