Saturday, September 7, 2013

Wrapper

https://docs.google.com/file/d/0B-swXJjVKED1amM4OU10M2x5Nmc/edit?usp=sharing

https://docs.google.com/file/d/0B-swXJjVKED1eXBIWmpzWlFQeVU/edit?usp=sharing

HttpWrapper.h


@class ASIFormDataRequest,HttpWrapper;

@protocol HttpWrapperDelegate


- (void) HttpWrapper:(HttpWrapper *)wrapper fetchDataSuccess:(NSString *)response;
- (void) HttpWrapper:(HttpWrapper *)wrapper fetchDataFail:(NSError *)error;

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

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

@end

@interface HttpWrapper : NSObject {
    
    ASIFormDataRequest *requestMain;
    
    NSObject<HttpWrapperDelegate> *delegate;
    //BOOL isImage;
}

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

-(void) requestWithMethod:(NSString*)method url:(NSString*)strUrl param:(NSMutableDictionary*)dictParam;
-(void)setVideoData:(NSString*)method url:(NSString*)strUrl param:(NSMutableDictionary*)dictParam;
-(void) requestWithImageUrl:(NSString*)strUrl toFolder:(NSString*)folderName;
-(void) cancelRequest;


@end

HttpWrapper.m

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

@implementation HttpWrapper

AppDelegate *appDelegate;

@synthesize delegate, fetchSuccess, fetchFail;

-(id)initWithDelegate:(id)del {
    self = [super init];
    if(self) {
        delegate = del;
        appDelegate = [AppDelegate sharedDelegate];
    }
    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];
   
    if ([[dic valueForKey:@"success"]intValue] == 0) {
        if ([dic valueForKey:@"msg"] != (id)[NSNull null]) {
            [appDelegate showAlert:@"Alert" message:[dic valueForKey:@"msg"]];
        }
    }
    request = nil;
}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"HttpWrapper > requestFailed > error: %@",error);
    
    request = nil;
    [appDelegate showAlert:@"Warning" message:@"Some Technical or Internet problem accure"];
    if([delegate respondsToSelector:fetchFail])
        [delegate performSelector:fetchFail withObject:error];
}

-(void) requestWithImageUrl:(NSString*)strUrl {

    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSString *filePath = [appDelegate applicationCacheDirectory] ;
    filePath = [filePath stringByAppendingPathComponent:[url lastPathComponent]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] == YES) {
        if([delegate respondsToSelector:@selector(fetchImageSuccess:)])
            [delegate performSelector:@selector(fetchImageSuccess:) withObject:filePath];
        
        return;
    }
    
    ASIFormDataRequest *requestMain = [ASIHTTPRequest requestWithURL:url];
    [requestMain setDidFinishSelector:@selector(requestFinishedImage:)];
    [requestMain setDidFailSelector:@selector(requestFinishedImage:)];
    [requestMain setDownloadDestinationPath:filePath];
    [requestMain setShouldContinueWhenAppEntersBackground:YES];
    [requestMain setDelegate:self];
    [requestMain startAsynchronous];
}

-(void) requestWithImageUrl:(NSString*)strUrl toFolder:(NSString*)folderName venueName:(NSString*)vn{
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSString *filePath = [[appDelegate applicationCacheDirectory] stringByAppendingPathComponent:folderName];
    
    filePath = [filePath stringByAppendingPathComponent:[vn stringByAppendingString:@".png"]];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath] == YES) {
        if([delegate respondsToSelector:@selector(fetchImageSuccess:)])
            [delegate performSelector:@selector(fetchImageSuccess:) withObject:filePath];
        
        return;
    }
    
    ASIFormDataRequest *requestMain = [ASIHTTPRequest requestWithURL:url];
    [requestMain setDidFinishSelector:@selector(requestFinishedImage:)];
    [requestMain setDidFailSelector:@selector(requestFinishedImage:)];
    [requestMain setDownloadDestinationPath:filePath];
    [requestMain setShouldContinueWhenAppEntersBackground:YES];
    [requestMain setDelegate:self];
    [requestMain startAsynchronous];
}

- (void)requestFinishedImage:(ASIHTTPRequest *)request
{
    //NSData *responseData = [request responseData];
    if([delegate respondsToSelector:@selector(fetchImageSuccess:)])
        [delegate performSelector:@selector(fetchImageSuccess:) withObject:[request downloadDestinationPath]];
    
    request = nil;
}

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

@end





Calling HttpWrapper method for Parsing :-


    if ([txtcommentText.text isEqualToString:@""]) {
        [appDelegate showAlertWithTitle:@"Alert" message:@"CommentBox is Empty Please Write the comment"];
    }
    else
    {
        if(sendCommentRequest)
        {
            [sendCommentRequest cancelRequest];
            [sendCommentRequest release];
            sendCommentRequest = nil;
        }
        
        [appDelegate showLoadingView];
        sendCommentRequest = [[HttpWrapper alloc] init];
        sendCommentRequest.delegate=self;
        
        NSString *strUrl =[NSString stringWithFormat:@"%@?action=addPostComment",serverURl];
        NSString *strPostId =[objUserImage valueForKey:@"postid"];
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *strUsername=[defaults objectForKey:@"username"];
        
        NSMutableDictionary *dictcomment = [NSMutableDictionary dictionary];
        [dictcomment setObject:strUsername forKey:@"username"];
        [dictcomment setObject:strPostId forKey:@"postid"];
        [dictcomment setObject:txtcommentText.text forKey:@"comment"];
        
        [sendCommentRequest requestWithMethod:@"POST" url:strUrl param:dictcomment];
        [UIView transitionWithView:commentView duration:1.0 options:UIViewAnimationOptionTransitionFlipFromRight animations:^{commentView.hidden=NO;} completion:nil];
        [commentView setHidden:YES];

    }

Httpwrapper delegate methods :-

(void)fetchDataFail:(NSError *)error
{
    [appDelegate hideLoadingView];
}
-(void)fetchDataSuccess:(NSString *)response{
    
    SBJSON *parser = [[SBJSON alloc] init];
    [parser retain];
    jsonDic=[parser objectWithString:response error:nil];
    [jsonDic retain];
    
    NSString *strStutas = [jsonDic objectForKey:@"message"];
    
    txtFirstName.hidden = TRUE;
    txtLastName.hidden = TRUE;
    txtCity.hidden = TRUE;
    btnProfileUpdate.hidden =TRUE;
    txtState.hidden = TRUE;
    txtFullName.hidden = FALSE;
    txtFullAdd.hidden = FALSE;
    
    if([strStutas isEqualToString:@"Success"])
    {
        // Delete all Previous Images ...
        [db deleteAllPrevProfileInfo];
        
        if (loadMore == FALSE) {
          
            [db deleteAllPrevProfilePostsInfo];
        }
        else
        {
            [db deleteAllPrevProfilePostsInfoWithMore];
        }
        
        if(result)
        {
            [result release];
            result = nil;
        }
        
        NSMutableDictionary *dicsUserData=[jsonDic objectForKey:@"result"];
        [dicsUserData retain];
                
       NSArray *dataresult =[dicsUserData objectForKey:@"posts"];
        
              
        if (dataresult) {

        for (NSMutableDictionary *objDic in dataresult) {
        
            ProfilePosts *obj = (ProfilePosts *)[NSEntityDescription insertNewObjectForEntityForName:@"ProfilePosts"
                                                                inManagedObjectContext:appDelegate.managedObjectContext];
            float expWidth = 320, expHeight, orgWidth, orgHeight;
            
            orgWidth = [[[objDic objectForKey:@"image_data"] objectForKey:@"width"] floatValue];
            orgHeight = [[[objDic objectForKey:@"image_data"] objectForKey:@"height"] floatValue];
            
            expHeight = (orgHeight * expWidth)/orgWidth;
            
            obj.postid = [objDic objectForKey:@"postid"];
            obj.imagetitle = [objDic objectForKey:@"imagetitle"];
            obj.imageurl = [objDic objectForKey:@"imageurl"];
            obj.imagedesc = [objDic objectForKey:@"imagedesc"];
            obj.is_portrait = [objDic objectForKey:@"is_portrait"];
            obj.username = [objDic objectForKey:@"username"];
            obj.datetime = [objDic objectForKey:@"datetime"];
            obj.photo = [dicsUserData objectForKey:@"photo"];
            obj.commentcount =[objDic objectForKey:@"comment_count"];
            obj.likecount =[objDic objectForKey:@"likecount"];
            obj.userlikecount =[NSNumber numberWithBool:[[objDic objectForKey:@"currentUserLike"] boolValue]];
            
            obj.img_height = [NSNumber numberWithFloat:expHeight];
            obj.img_width = [NSNumber numberWithFloat:expWidth];
            
            [appDelegate saveAction];
            }
        }
       
         ////// Full name
        NSString *fname = [dicsUserData objectForKey:@"FirstName"];
        fname = [fname stringByAppendingString:@" "];
        NSString *fullname = [fname stringByAppendingString:[dicsUserData objectForKey:@"LastName"]];
        
        //// City, State
        NSString *strConcate;
        if ([[dicsUserData objectForKey:@"State"] isEqualToString:@""]) {
            strConcate = [NSString stringWithFormat:@" "];
        }
        else{
            strConcate = [NSString stringWithFormat:@", "];
        }
        //// City, State
        NSString *city = [[dicsUserData objectForKey:@"City"] stringByAppendingString:strConcate];
        NSString *fullAdd = [city stringByAppendingString:[dicsUserData objectForKey:@"State"]];
        
        txtFullName.text = fullname;
        txtFullAdd.text = fullAdd;

        result = [db getLastImages];
        [result retain];
        [tblView reloadData];
        
        if ([[dicsUserData objectForKey:@"photo"] isEqualToString: @""]) {
            
            ivPhoto.image = [UIImage imageNamed:@"noImage.png"];
        }
        
        if (!result) {
            
            ProfilePosts *arrGetUserProfile = (ProfilePosts *)[result objectAtIndex:0];
            NSURL *imgURL = [NSURL URLWithString:arrGetUserProfile.photo];
            NSString *strImg = [NSString stringWithContentsOfURL:imgURL
                                                        encoding:NSStringEnumerationByParagraphs
                                                           error:errno];
//            ivPhoto.image = [UIImage imageWithData:imgData];
            [asyncImg loadImageFromStringforUserimg:strImg];
        }else{
  
            NSString *imgStr = [NSString stringWithFormat:@"%@", [dicsUserData objectForKey:@"photo"]];
            [asyncImg loadImageFromStringforUserimg:imgStr];
        }

        btnProfileUpdate.hidden=FALSE;
       
    }
    
    [appDelegate hideLoadingView];
    [jsonDic release];
    [parser release];

}

OR another methods way of implementing :-


-(void)HttpWrapper:(HttpWrapper *)wrapper fetchDataFail:(NSError *)error{
    [appDelegate hideLoadingView];
    if(wrapper == likeRequest)
    {
        [appDelegate showAlertWithTitle:@"Like"
                                message:@"Error while sending like"];
    }
    else if(wrapper == commentsRequest)
    {
        [appDelegate showAlertWithTitle:@"Comment"
                                message:@"Error while fetching comments"];
    }
    if(wrapper == sendCommentRequest)
    {
        [appDelegate showAlertWithTitle:@"Comment"
                                message:@"Error while posting comment"];
    }
}

-(void)HttpWrapper:(HttpWrapper *)wrapper fetchDataSuccess:(NSString *)response{
    
    SBJSON *parser = [[SBJSON alloc] init];
    NSLog(@"Response : %@",response);
    
    if(wrapper == likeRequest)
    {
        dictDetail =  [parser objectWithString:response];
        [dictDetail retain];
        NSString *counterlike=[dictDetail objectForKey:@"totalLikes"];
        [lblLike setText:[NSString stringWithFormat:@"%@",counterlike]];
        
        BOOL currentUserLike = [[dictDetail objectForKey:@"currentUserLike"] boolValue];
        if (currentUserLike == TRUE) {
            
            UIImage* imageBtn = [UIImage imageNamed:@"favoritered@2x.png"];
            [btnLike setBackgroundImage:imageBtn forState:UIControlStateNormal];
        }
        else{
            
            UIImage* imageBtn = [UIImage imageNamed:@"favorite.png"];
            [btnLike setBackgroundImage:imageBtn forState:UIControlStateNormal];
        }
        
    }
    else if(wrapper == commentsRequest)
    {
        dictComment =[parser objectWithString:response];
        [dictComment retain];
        
        NSString *counterlike=[dictComment objectForKey:@"totalLikes"];
        [lblLike setText:[NSString stringWithFormat:@"%@",counterlike]];
        
        arrComments = [dictComment objectForKey:@"results"];
        NSString *countstr = [NSString stringWithFormat:@"%d",arrComments.count];
        [lblComment setText:countstr];
        
        BOOL currentUserLike = [[dictComment objectForKey:@"currentUserLike"] boolValue];
        if (currentUserLike == TRUE) {
            
            UIImage* imageBtn = [UIImage imageNamed:@"favoritered@2x.png"];
            [btnLike setBackgroundImage:imageBtn forState:UIControlStateNormal];
        }
        else{
            
            UIImage* imageBtn = [UIImage imageNamed:@"favorite.png"];
            [btnLike setBackgroundImage:imageBtn forState:UIControlStateNormal];
        }
        [tblView reloadData];
    }
    else if(wrapper == sendCommentRequest)
    {
        [self fetchComments];
    }
    [parser release];
    [appDelegate hideLoadingView];

}


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



Saturday, April 6, 2013

Load imgge from nscatchdirectory And Store image to catchDirecoty


This code to fetch image to catchDirecoty

-(void)fetchImageFromCatch{
    if (imgProfile.image!=nil) {
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [self applicationCacheDirectory];
        filePath = [filePath stringByAppendingPathComponent:@"anyImageName.png"];
        if ([fileManager fileExistsAtPath:filePath] == YES) {
          NSMutableDictionary *dictImage=[[NSMutableDictionary alloc]init];
           [dictImage setValue:filePath forKey:@"filepath"];
            [dictImage setValue:@"productImage" forKey:@"filekey"];
            [dic setValue:dictImage forKey:@"productImage"];
        }
    }
}

This code to write image to catchDirecoty

-(void)WriteImageToCatch{
    UIImage *image = [UIImage imageNamed:@"anyImageName.png"];
     NSString *filePath = [self applicationCacheDirectory];
        filePath = [filePath stringByAppendingPathComponent:@"itemImage.png"];
NSData *data1 = [NSData dataWithData:UIImagePNGRepresentation(image)]; NSError *writeError = nil; [data1 writeToFile:filePath options:NSDataWritingAtomic error:&writeError]; if (writeError) { NSLog(@"Error writing file: %@", writeError); }
}

This Functiuon for get path to catchDirecoty

-(NSString *) applicationCacheDirectory {

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);

NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0]:nil;

 return basePath;

}




Monday, August 13, 2012

UITableview Demo-Example cell value over writing

Download Demo From Hear..... 

--------------------------------------------------------AppDelegate.h--------------------------------------------------
#import <UIKit/UIKit.h>

@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

@property (strong, nonatomic) ViewController *viewController;

@end  

---------------------------------------------------------AppDelegate.m-------------------------------------------------

#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

@synthesize window = _window;
@synthesize viewController = _viewController;

- (void)dealloc
{
    [_window release];
    [_viewController release];
    [super dealloc];
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch.
    self.viewController = [[[ViewController alloc] initWithNibName:@"ViewController" bundle:nil] autorelease];
    self.window.rootViewController = self.viewController;
    [self.window makeKeyAndVisible];
    return YES;
}

@end
----------------------------------------------------ViewController.xib----------------------------------------------------

 in xib drag adn drop tableview in view

then give reffernce to it....
reference to delegate....also



----------------------------------------------------ViewController.h----------------------------------------------------

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    IBOutlet UITableView *tbl;
}
@property(nonatomic,retain) IBOutlet UITableView *tbl;
@end


--------------------------------------------------ViewController.m------------------------------------------------------

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

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

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

// Return how many rows in the table
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 10;
}

// Return a cell for the ith row
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Use re-usable cells to minimize the memory load
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nil];
//dequeueReusableCellWithIdentifier:nil is not overload the cell value
    if (!cell)  {
        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:nil] autorelease];
//reuseIdentifier:nil is not overload the cell value both place must use....
    }
   
    // Set up the cell's text
    cell.textLabel.text = [[UIFont familyNames] objectAtIndex:[indexPath row]];
   // cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;



//the above line show discloser button (arrow button) in all cell
//    cell.hidesAccessoryWhenEditing = NO;
    return cell;
}
@end