Sunday, September 8, 2013

AppDelegate

AppDelegate.h

@interface AppDelegate : UIResponder <UIApplicationDelegate,MBProgressHUDDelegate>
{
    
    UIImageView *splashView;
    UIView *loadView;
    
    UIActivityIndicatorView *spinningWheel;
    NSMutableDictionary *dirUserInfo;
    
    HomeViewController *objHomeView;
    UINavigationController *navHome;
    
    NotesView *objNotesView;
    UINavigationController *navNotes;
    
    UploadView *objUploadView;
    UINavigationController *navUpload;
    
    ResearchView *objResearchView;
    UINavigationController *navResearch;
    
    ForumView *objForumView;
    UINavigationController *navForum;
    
    RecordDetailView *objRecordDet;
    UINavigationController *navRecordDet;
    
    TabBarIphone *tabBarController;
    DBHelper *objHelper;
    
}

AppDelegate.m


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
   // [[UIApplication sharedApplication] setStatusBarHidden:YES];
    NSLog(@"appp started");
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
     objHelper = [[DBHelper alloc] init];
        
    // Override point for customization after application launch.
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {

         if (isiPhone5) {
            splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 568)];
            splashView.image = [UIImage imageNamed:@"Default-568h@2x"];
        }
        else
        {
            splashView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 480)];
            splashView.image = [UIImage imageNamed:@"Default"];
        }
      
        [self.window addSubview:splashView];
        [self.window makeKeyAndVisible];
        [self performSelector:@selector(loadViewIphone) withObject:nil afterDelay:2.0];
    }
    else 
    {
        splashView = [[UIImageView alloc] initWithFrame:ipadFrame];
        splashView.image = [UIImage imageNamed:@"Default_iPad"];
        [self.window addSubview:splashView];
        [self.window makeKeyAndVisible];
        [self performSelector:@selector(loadViewIpad) withObject:nil afterDelay:2.0];
    }
    [self.window makeKeyAndVisible];
    return YES;
}
-(BOOL)application:(UIApplication *)application
           openURL:(NSURL *)url
 sourceApplication:(NSString *)sourceApplication
        annotation:(id)annotation
{
    // Make sure url indicates a file (as opposed to, e.g., http://)
    if (url != nil && [url isFileURL]) {
        // Tell our OfflineReaderViewController to process the URL
        
        [self attributesForFile:url];
        [self saveFileToDocuments:url];
        [objUploadView handleDocumentOpenURL:url];
    }
        // Indicate that we have successfully opened the URL
    return YES;
}
-(void)loadViewIphone 
{
    [splashView removeFromSuperview];
    LoginView *objLoginView = [[[LoginView alloc] initWithNibName:@"LoginView" bundle:nil] autorelease];
    self.navigationController = [[[UINavigationController alloc] initWithRootViewController:objLoginView] autorelease];
    self.window.rootViewController = self.navigationController;
    [self.window makeKeyAndVisible];
    CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:kCATransitionFade];
[animation setDuration:0.5];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:
  kCAMediaTimingFunctionEaseInEaseOut]];
[[self.window layer] addAnimation:animation forKey:kAnimationKey];
}
-(void)loadViewIpad 
{
    [splashView removeFromSuperview];
    MasterViewController *masterViewController = [[[MasterViewController alloc] initWithNibName:@"MasterViewController_iPad" bundle:nil] autorelease];
    UINavigationController *masterNavigationController = [[[UINavigationController alloc] initWithRootViewController:masterViewController] autorelease];
    
    self.window.rootViewController = masterNavigationController;
    [self.window makeKeyAndVisible];
    CATransition *animation = [CATransition animation];
[animation setDelegate:self];
[animation setType:kCATransitionFade];
[animation setDuration:0.5];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:
  kCAMediaTimingFunctionEaseInEaseOut]];
[[self.window layer] addAnimation:animation forKey:kAnimationKey];
}
-(void)initializeTabbar
{
    UIImage *img;
    
    img = [UIImage imageNamed:@"profile.png"];
    objHomeView = [[HomeViewController alloc] initWithNibName:@"HomeViewController" bundle:nil];
    navHome = [[UINavigationController alloc] initWithRootViewController:objHomeView];    
    [objHomeView.tabBarItem initWithTitle:@"Home" image:img tag:1];
    
    img = [UIImage imageNamed:@"note.png"];
    objNotesView = [[NotesView alloc] initWithNibName:@"NotesView" bundle:nil];
    navNotes = [[UINavigationController alloc] initWithRootViewController:objNotesView];
    [objNotesView.tabBarItem initWithTitle:@"Notes" image:img tag:2];

    img = [UIImage imageNamed:@"iPhoto.png"];
    objUploadView = [[UploadView alloc] initWithNibName:@"UploadView" bundle:nil];
    navUpload = [[UINavigationController alloc] initWithRootViewController:objUploadView];
    [objUploadView.tabBarItem initWithTitle:@"Upload" image:img tag:3];

    img = [UIImage imageNamed:@"search.png"];
    objResearchView = [[ResearchView alloc] initWithNibName:@"ResearchView" bundle:nil];
    navResearch = [[UINavigationController alloc] initWithRootViewController:objResearchView];
    [objResearchView.tabBarItem initWithTitle:@"Research" image:img tag:4];
    
    img = [UIImage imageNamed:@"Forum1.png"];
    objForumView = [[ForumView alloc] initWithNibName:@"ForumView" bundle:nil];
    navForum = [[UINavigationController alloc] initWithRootViewController:objForumView];
    [objForumView.tabBarItem initWithTitle:@"Forum" image:img tag:5];
    
    tabBarController =[[TabBarIphone alloc] init];
    tabBarController.viewControllers = [NSArray arrayWithObjects:
                                        [self sideMenu].navigationController,
                                        self.navNotes,
                                        self.navUpload,
                                        self.navResearch,
                                        self.navForum,
                                        nil];
}



- (void) showAlertWithTitle:(NSString *)title message:(NSString *)message {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:message delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
}
+(NSDate *) dateFromString:(NSString *)string
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"yyyy-MM-dd"];
    return [formater dateFromString:string];
}
+(NSString *) stringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"yyyy-MM-dd"];
    return [formater stringFromDate:date];
}
-(NSDate *)convertStringToDate:(NSString *) date format:(NSString *)format {
    
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease];
    [formatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
    
NSDate *nowDate = [[[NSDate alloc] init] autorelease];
[formatter setDateFormat:format];
nowDate = [formatter dateFromString:date];
    
return nowDate;
}
+(AppDelegate *)sharedAppDelegate {
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
-(NSString*) trimString:(NSString *)theString {
NSString *theStringTrimmed = [theString stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceAndNewlineCharacterSet]];
return theStringTrimmed;
}
-(NSString *) removeNull:(NSString *) string {    
    
NSRange range = [string rangeOfString:@"null"];
    //NSLog(@"in removeNull : %d  >>>> %@",range.length, string);
if (range.length > 0 || string == nil) {
string = @"";
}
string = [self trimString:string];
return string;
}

-(UIToolbar *)getNumberKeyboardToolbarWithTarget:(id)target
                                    DoneSelector:(SEL)doneSelector
                                  CancelSelector:(SEL)cancelSelector
{
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleBlackTranslucent;
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:@"Cancel" style:UIBarButtonItemStyleBordered target:target action:cancelSelector],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:target action:doneSelector],
                           nil];
    [numberToolbar sizeToFit];
    return numberToolbar;
}
-(void) setDatePickerForTextField:(UITextField *)textfield
                   datePickerMode:(UIDatePickerMode)mode
                           Target:(id)target
                     DoneSelector:(SEL)doneSelector
                   CancelSelector:(SEL)cancelSelector
{
    UIDatePicker *picker = [[[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 216)] autorelease];
    picker.datePickerMode = mode;
    
    if(mode == UIDatePickerModeTime)
        picker.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"NL"];
    else
        picker.locale = nil;
    
   // textfield.inputAccessoryView = [self getNumberKeyboardToolbarWithTarget:target DoneSelector:doneSelector CancelSelector:cancelSelector];
    textfield.inputView = picker;
}
-(NSString *) stringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"dd-MM-yyyy"];
    return [formater stringFromDate:date];
}
-(NSString *) timeStringFromDate:(NSDate *)date
{
    NSDateFormatter *formater = [[[NSDateFormatter alloc] init] autorelease];
    [formater setDateFormat:@"HH:mm"];
    return [formater stringFromDate:date];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
     */
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
    /*
     Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
     */
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}
- (void)applicationWillTerminate:(UIApplication *)application
{
    // Saves changes in the application's managed object context before the application terminates.
    [self saveContext];
}
- (void)saveContext
{
    NSError *error = nil;
    NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
    if (managedObjectContext != nil)
    {
        if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error])
        {
            /*
             Replace this implementation with code to handle the error appropriately.
             
             abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
             */
            NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
            abort();
        } 
    }
}
#pragma mark - Core Data stack
/**
 Returns the managed object context for the application.
 If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
 */
- (NSManagedObjectContext *)managedObjectContext
{
    if (__managedObjectContext != nil)
    {
        return __managedObjectContext;
    }
    
    NSPersistentStoreCoordinator *coordinator = [self persistentStoreCoordinator];
    if (coordinator != nil)
    {
        __managedObjectContext = [[NSManagedObjectContext alloc] init];
        [__managedObjectContext setPersistentStoreCoordinator:coordinator];
    }
    return __managedObjectContext;
}
/**
 Returns the managed object model for the application.
 If the model doesn't already exist, it is created from the application's model.
 */
- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil)
    {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"stratus" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    
    return __managedObjectModel;
    
}
/**
 Returns the persistent store coordinator for the application.
 If the coordinator doesn't already exist, it is created and the application's store added to it.
 */
- (NSPersistentStoreCoordinator *)persistentStoreCoordinator
{
    if (__persistentStoreCoordinator != nil)
    {
        return __persistentStoreCoordinator;
    }
    
    NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:@"stratus.sqlite"];
        
    NSError *error = nil;
    __persistentStoreCoordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:[self managedObjectModel]];
    if (![__persistentStoreCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:storeURL options:nil error:&error])
    {
        /*
         Replace this implementation with code to handle the error appropriately.
         
         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         
         Typical reasons for an error here include:
         * The persistent store is not accessible;
         * The schema for the persistent store is incompatible with current managed object model.
         Check the error message to determine what the actual problem was.
         
         
         If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
         
         If you encounter schema incompatibility errors during development, you can reduce their frequency by:
         * Simply deleting the existing store:
         [[NSFileManager defaultManager] removeItemAtURL:storeURL error:nil]
         
         * Performing automatic lightweight migration by passing the following dictionary as the options parameter: 
         [NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES], NSMigratePersistentStoresAutomaticallyOption, [NSNumber numberWithBool:YES], NSInferMappingModelAutomaticallyOption, nil];
         
         Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
         
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }    
    return __persistentStoreCoordinator;
}
-(NSString *)saveFileToDocuments:(NSURL *)url {
    
     NSLog(@">>>>>>>>>>>>>>>>>>>>>>>>>>>> to save");
      
    fileName = [url lastPathComponent];
    storePath =[[self applicationDocumentCacheDirectory]stringByAppendingPathComponent:fileName];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if ([fileManager fileExistsAtPath:storePath] == YES) {
        NSLog(@"removeItemAtPath >>>>>>>>>>>>>>>>>> saveFileToDocuments 1 :%@", storePath);
        [[NSFileManager defaultManager] removeItemAtPath:storePath error:NULL];
    }
    
    NSError * error = nil;
    if (url == nil) {
        return nil;
    }
    
    [[NSFileManager defaultManager] copyItemAtURL:url
                                            toURL:[NSURL fileURLWithPath:storePath]
                                            error:&error];
    
    
    if ( error ) {
        NSLog(@"%@", error);
        NSLog(@"removeItemAtPath >>>>>>>>>>>>>>>>>> saveVideoToDocuments 2 :%@", storePath);
        [[NSFileManager defaultManager] removeItemAtPath:storePath error:NULL];
        return nil;
    }
    
    NSData * DocData = [NSData dataWithContentsOfURL:url];
    [DocData writeToFile:storePath atomically:YES];
    [storePath retain];

  //  [objUploadView ReloadView];
    return storePath;
}


#pragma mark - Application's Documents directory
#pragma mark - Document Directory Path
-(NSString *)applicationDocumentCacheDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

}

ImagePicker Delegate Methods

ImagePicker Delegate Methods :-

-(void)SaveImage
{
 if (imageView.image != nil) {
            
            UIImage *image = imageView.image;
            
            NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
            NSString *strUser = [prefs valueForKey:@"username"];
            [strUser retain];
            NSString * strUserLocal = [objinsurance.insurance_id stringByAppendingString:@".png"];
            
            NSString *imagePath = [[appDelegate applicationDocumentCacheDirectory] stringByAppendingPathComponent:strUserLocal];
            NSLog(@"Path by Image To SAVE :::::>>>%@<<<<<<",imagePath);
            
            NSData *data = [NSData dataWithData:UIImagePNGRepresentation(image)];
            
            if(data != nil) {
                [data writeToFile:imagePath atomically:YES];
                NSLog(@">>>>>>>>>>>>>>>>>>> Image Going To Write <<<<<<<<<<<");
                
               objinsurance.picture = imagePath;
            }
            else
            {
                [[NSFileManager defaultManager] removeItemAtPath:imagePath error:NULL];
                NSLog(@">>>>>>>>>>>>>>>>>>>   Error Writing Image File to Directory      <<<<<<<<<<<");
            }
            
        }else{
            
            NSLog(@"nil");
        }
}

-(IBAction)onClickPicture:(id)sender
{
    UIActionSheet *action = [[UIActionSheet alloc] initWithTitle:@"Attach A Picture" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Take Picture From Camera",@"Picture From gallery",nil];
    action.actionSheetStyle = UIActionSheetStyleDefault;
    [action showInView:self.tabBarController.tabBar];
    [action release];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    UIImagePickerController *imgPicker = [[UIImagePickerController alloc] init];
    if (buttonIndex == 0)
    {
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])  {
            imgPicker.sourceType = UIImagePickerControllerSourceTypeCamera;
            imgPicker.showsCameraControls = YES;
            imgPicker.wantsFullScreenLayout = YES;
            imgPicker.delegate = self;
            
            CGAffineTransform cameraTransform = CGAffineTransformMakeScale(1.132, 1.132);
            imgPicker.cameraViewTransform = cameraTransform;
            
            UIView *headsUpView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
            [imgPicker setCameraOverlayView:headsUpView];
            
            [self presentModalViewController:imgPicker animated:YES];
            [imgPicker release];
            [headsUpView release];
        }
        else
        {
            UIAlertView *altnot=[[UIAlertView alloc]initWithTitle:@"Camera Not Available" message:@"Camera Not Available" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            altnot.tag=103;
            [altnot show];
            [altnot release];
        }
    }
    else if(buttonIndex == 1)
    {
        imgPicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imgPicker.delegate = self;
        [self presentViewController:imgPicker animated:YES completion:nil];
        [imgPicker release];
    }
    [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    UIImage *tempImg= [appDelegate scaleAndRotateImage:image];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    imageView.image = tempImg;

}

Custom cell

Customcell.h

#import <UIKit/UIKit.h>
#import "AsyncImage.h"
#import "GalleryImageInfo.h"

@interface CommentCell : UITableViewCell
{
    IBOutlet AsyncImage *objAsyncUser;
    IBOutlet UILabel *lblComment;
    IBOutlet UILabel *lblUsername;
    IBOutlet UILabel *lblDateTime;
           
    GalleryImageInfo *objItem;
    NSDictionary *objdict;
    
    UIImageView *photo;
    CGFloat *cellHeight;
}
-(IBAction)flagTapped:(id)sender;
-(void)setObjItem:(NSDictionary *)data;
-(void)loadImage;
-(CGFloat)getCellHeight;

@property(nonatomic) CGFloat *cellHeight;
@property(nonatomic,retain)IBOutlet UILabel *lblComment;
@property(nonatomic,retain)IBOutlet UILabel *lblUsername;
@property(nonatomic,retain)IBOutlet UILabel *lblDateTime;
@property(nonatomic,retain)IBOutlet AsyncImage *objAsyncUser;

@end

Customcell.m

-(void)setObjItem:(NSDictionary *)data
{
    objdict = data;
    lblComment.text =[data valueForKey:@"comment"];
    lblUsername.text=[data valueForKey:@"username"];
    lblDateTime.text =[data valueForKey:@"comment_date"];
    lblComment.text= [lblComment.text stringByTrimmingCharactersInSet:
                      [NSCharacterSet whitespaceAndNewlineCharacterSet]];

    [lblComment sizeToFit];
    lblDateTime.frame =CGRectMake(66, lblComment.frame.size.height+25, 207, 21);
    
    
}
-(void)loadImage
{
    [objAsyncUser loadImageFromStringforUserimg:[objdict valueForKey:@"userPhoto"]];

}


CustomCellBean.h

#import <UIKit/UIKit.h>

@protocol AllPicsDelegate <NSObject>

@required
-(void)AllpicsReload : (int)sectionNo;

@end
@class AllPicsView;
@interface CustomCellAllPics : UITableViewCell<AsyncImageDelegate>
{
    
    GalleryImageInfo *ObjItem;
    AllPicsView *objallPics;
   

}
-(void)loadImage;
- (void)setObjItem:(GalleryImageInfo *)newItem;
@end


CustomCellBean.m


- (void)setObjItem:(GalleryImageInfo *)newItem
{
    ObjItem =newItem;
    if (ObjItem!=nil)
    {
        lblUserName.text = ObjItem.username;
        lblImageDescription.text =ObjItem.imgdescription;
        lblImageTitle.text =ObjItem.imagetitles;
        lblDateTime.text=ObjItem.datetime;
        lblComment.text=ObjItem.commentcount;
        lblLike.text =ObjItem.likecount;
        
     
        if ([ObjItem.currentuserlike isEqualToNumber:[NSNumber numberWithInt:1]])
        {
            imgfav.image = [UIImage imageNamed:@"favoritered@2x.png"];
        }
        else{
            imgfav.image = [UIImage imageNamed:@"favorite.png"];
        }
    }
}

-(void)loadImage
{

    [AsyncUserImg loadImageFromStringforUserimg:ObjItem.userImage];
    
    AsyncImg.delegate = self;
    AsyncUserImg.delegate = self;
    [self retain];
}




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

}