Saturday, September 14, 2013

TouchXml Demo

Image processes in particular View using Async

Image processes in particular View using Async :-

In xib take one View n give reference of asyncimage

- (void)viewDidLoad
{
    [super viewDidLoad];


scroller =[[CustomScrollBar alloc]initWithFrame:CGRectMake(0,44,
                                        320,460)];
    
    scroller.maximumZoomScale = 4.0;
    scroller.minimumZoomScale = 1.0;
    scroller.clipsToBounds = YES;
    scroller.scrollEnabled = YES;
    scroller.multipleTouchEnabled = YES;
    scroller.userInteractionEnabled = YES;
    scroller.showsHorizontalScrollIndicator = YES;
    scroller.showsVerticalScrollIndicator = YES;
    scroller.scrollsToTop = NO;
    scroller.delegate = self;
    scroller.del = self;
    scroller.contentSize = CGSizeMake(scroller.frame.size.width,
                                      scroller.frame.size.height);
    
    float x = asyImg.bounds.size.width/2;
    float y = (asyImg.bounds.size.height/2);
    asyImg.center = CGPointMake(x, y);
    [asyImg setFrame:CGRectMake(0,44, 320, 290)];
    [scroller addSubview:asyImg];
    self.view.clipsToBounds = YES;
    [self.view addSubview:scroller];
    
       
    [asyImg loadImageFromString:[objImage valueForKey:@"image"] dict:nil];

}

#pragma mark -
#pragma mark scrollView Delegate Methods
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return asyImg;
}
#pragma mark -
#pragma mark Touch Delegate Methods
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 1) {
        [scroller setZoomScale:1.0];
        [self setViewAnimation:CGRectMake(10, 65, 320, 350)];
    }
}
-(void) setViewAnimation:(CGRect)frame {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
    asyImg.frame = self.view.frame;
    scroller.contentSize = self.view.frame.size;
    [UIView commitAnimations];
}


If we want to Post Image :-


-(void)imageUpload
{

  request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];
    [request setRequestMethod:@"POST"];
    [request setTimeOutSeconds:120];
    
    [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        NSString *strUser = [prefs valueForKey:@"username"];
        [strUser retain];
        NSString * strUserLocal = [strUser stringByAppendingString:@".jpeg"];
        NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:strUserLocal];


[request setPostValue:@"png" forKey:@"type"];
    [request setFile:fetchPath withFileName:imageName andContentType:@"image/ jpg" forKey:@"image"];


    [request setUseCookiePersistence:NO];
    [request setUseSessionPersistence:NO];
    
    [request setDelegate:self];
    [request setDidFinishSelector:@selector(requestFinished:)];
    [request setDidFailSelector:@selector(requestFailed:)];
    [request setShowAccurateProgress:YES];
    [request startAsynchronous];


}

OR Other Way to Upload Photo :-


- (UIImage *)imageByScalingProportionallyToSize:(CGSize)targetSize {
  UIImage *sourceImage = self;
  UIImage *newImage = nil;
  
  CGSize imageSize = sourceImage.size;
  CGFloat width = imageSize.width;
  CGFloat height = imageSize.height;
  
  CGFloat targetWidth = targetSize.width;
  CGFloat targetHeight = targetSize.height;
  
  CGFloat scaleFactor = 0.0;
  CGFloat scaledWidth = targetWidth;
  CGFloat scaledHeight = targetHeight;
  
  CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
  
  if (CGSizeEqualToSize(imageSize, targetSize) == NO) {
    
    CGFloat widthFactor = targetWidth / width;
    CGFloat heightFactor = targetHeight / height;
    
    if (widthFactor < heightFactor)
      scaleFactor = widthFactor;
    else
      scaleFactor = heightFactor;
    
    scaledWidth  = width * scaleFactor;
    scaledHeight = height * scaleFactor;
    
    // center the image
    
    if (widthFactor < heightFactor) {
      thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
    } else if (widthFactor > heightFactor) {
      thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
    }
  }
  
  
  // this is actually the interesting part:
  
  UIGraphicsBeginImageContext(targetSize);
  
  CGRect thumbnailRect = CGRectZero;
  thumbnailRect.origin = thumbnailPoint;
  thumbnailRect.size.width  = scaledWidth;
  thumbnailRect.size.height = scaledHeight;
  
  [sourceImage drawInRect:thumbnailRect];
  
  newImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  
  if(newImage == nil) NSLog(@"could not scale image");
  
  
  return newImage ;
}



-(void)imageUpload
{

NSURL *strUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@? action=addComment",Server_URL_MOBICH]];
        
    request = [[[ASIFormDataRequest alloc] initWithURL:strUrl] autorelease];        
    NSData *imageData = nil;
UIImage *image;
    if (image !=nil) {
            UIImage *newImage = [image imageByScalingProportionallyToSize:CGSizeMake(600, 600)];
            imageData = UIImageJPEGRepresentation(newImage, 0.9);
            [request setData:imageData forKey:@"image"];
            [request setPostValue:@"png" forKey:@"type"];
            [request setPostValue:@"ImageType" forKey:@"comment_type"];
        }
        
    
            [request setRequestMethod:@"POST"];
            [request setTimeOutSeconds:120];
            
            [request addRequestHeader:@"Content-Type" value:@"multipart/form-data"];
            [request setUseCookiePersistence:NO];
            [request setUseSessionPersistence:NO];
            
            [request setDelegate:self];
            [appDelegate showLoadingView];
            [request setDidFinishSelector:@selector(requestFinished:)];
            [request setDidFailSelector:@selector(requestFailed:)];
            [request setShowAccurateProgress:YES];
            [request startAsynchronous];
        }
}

Way to Save Image in CoreData :-


-(void)btnBarSave
{

if(!self.objinsurance)
    {
        objinsurance =(Insurance *)[appDelegate.objHelper createObjectForEntity:Entity_Insurance];
    }

objinsurance.name = txtName.text;
        objinsurance.insurance_id = txtInsuranceId.text;
   
        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");
        }
       
        [appDelegate saveContext];
        [appDelegate showAlertWithTitle:@"" message:@"Data Saved Successfully"];

}


To View Image from CoreData for edit:-


{
txtName.text = objinsurance.name;

  NSData *data = [NSData dataWithContentsOfFile:objinsurance.picture];
    imageView.image = [UIImage imageWithData:data];
}


DBHelper Classes :-


DBHelper.h


#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface DBHelper : NSObject {

}


DBHelper.m


@implementation DBHelper

AppDelegate *appDelegate;

-(id) init {
    
    if((self = [super init])) {
        appDelegate = [AppDelegate sharedAppDelegate];
    }
    return self;
}


#pragma mark -
#pragma mark - Creating Object

-(id)createObjectForEntity:(NSString *)entityName
{
    if (entityName!=nil || [entityName isEqualToString:@""])
    {
        return [NSEntityDescription
                insertNewObjectForEntityForName:entityName
                inManagedObjectContext:appDelegate.managedObjectContext];
    }
    else{
        return nil;
    }
}
-(id)createObjectForEntity:(NSString *)entityName context:(NSManagedObjectContext *)aContext
{
    if (entityName!=nil || [entityName isEqualToString:@""])
    {
        return [NSEntityDescription
                insertNewObjectForEntityForName:entityName
                inManagedObjectContext:aContext];
    }
    else{
        return nil;
    }
}


#pragma mark -
#pragma mark - Retrive Object

-(NSMutableArray*) getObjectsforEntity:(NSString *)strEntity ShortBy:(NSString *)strShort isAscending:(BOOL)ascending predicate:(NSPredicate *)predicate
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:strEntity inManagedObjectContext:appDelegate.managedObjectContext];
    [fetchRequest setEntity:entity];
    
    [fetchRequest setIncludesPendingChanges:NO];
    
    if (strShort)
    {
        NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:strShort ascending:ascending];
        
        [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
        [sort release];
    }
    if (predicate)
    {
        [fetchRequest setPredicate:predicate];
    }
    NSError *error;
    NSMutableArray *arrAllObjects = (NSMutableArray*)[appDelegate.managedObjectContext executeFetchRequest:fetchRequest error:&error];
[arrAllObjects retain];
    
    [fetchRequest release];
    
    return arrAllObjects;
}

#pragma mark -
#pragma mark path for Document Directory 

-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}



CustomScrollBarDelegate


CustomScrollBarDelegate.h


@protocol CustomScrollBarDelegate

@required
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event;
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event;

@optional

@end

CustomScrollBar

CustomScrollBar.h


#import <UIKit/UIKit.h>

#import "CustomScrollBarDelegate.h"

@interface CustomScrollBar : UIScrollView {
@public
NSObject<CustomScrollBarDelegate> *del;
}
@property (nonatomic, assign) NSObject<CustomScrollBarDelegate> *del;

@end

CustomScrollBar.m

#import "CustomScrollBar.h"

@implementation CustomScrollBar

@synthesize del;

#pragma mark -
#pragma mark Touch Delegate methods 
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesBeganScroll:withEvent:)]) {
        [del touchesBeganScroll:touches withEvent:event];
    }
}

- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesMovedScroll:withEvent:)]) {
        [del touchesMovedScroll:touches withEvent:event];
    }
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
if ([del respondsToSelector:@selector(touchesEndedScroll:withEvent:)]) {
        [del touchesEndedScroll:touches withEvent:event];
    }
}

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


@end

EmergencyContact

#define HelveticaRegular(s) [UIFont fontWithName:@"Helvetica" size:s]

#import <UIKit/UIKit.h>
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "Emergency_Contact.h"

EmergencyContact.h

@interface EmergencyContact : UIViewController<UITableViewDelegate,UITableViewDataSource,ABPeoplePickerNavigationControllerDelegate>{

     
    IBOutlet UITextField *txtName;
    IBOutlet UITextField *txtEmail, *txtPhone;
    IBOutlet UITableView *tblContact;
    
    IBOutlet UIScrollView *scrView;
    
    NSMutableArray *tempArray;
    IBOutlet UIButton *btnSave;
}
@property(nonatomic,strong) NSString *strAllInfo;
@property(nonatomic,retain)Emergency_Contact *objEmergencybean;
@property (nonatomic, retain) NSMutableArray *contactsArray;
@property (nonatomic, retain) ABPeoplePickerNavigationController *contacts;
@property(nonatomic,retain)IBOutlet UIScrollView *scrView;

@end

EmergencyContact.m


#import "EmergencyContact.h"
#import "AppDelegate.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>


@interface EmergencyContact ()

@end

@implementation EmergencyContact

AppDelegate *appDelegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Emergency Contact";
       
    UIBarButtonItem *btnadd = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact)];
    self.navigationItem.rightBarButtonItem = btnadd;
    [btnadd release];
    
}

-(void)addContact{
    
    contacts = [[ABPeoplePickerNavigationController alloc] init];
   [contacts setPeoplePickerDelegate:self];
    
   [contacts setDisplayedProperties:[NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonEmailProperty]]];
    [contacts setDisplayedProperties:[NSArray arrayWithObject:[NSNumber numberWithInt:kABPersonPhoneProperty]]];
  
[self presentModalViewController:contacts animated:YES];
}

#pragma mark - AddressBook Delegate Methods

-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person{
    return YES;
}
-(BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier{
    
     NSString *firstName = (NSString *)ABRecordCopyValue(person, kABPersonFirstNameProperty);
    NSString *lastName = (NSString *)ABRecordCopyValue(person, kABPersonLastNameProperty);
    
         
    // Compose the full name.
    NSString *fullName = @"";
    // Before adding the first and the last name in the fullName string make sure that these values are filled in.
    if (firstName != nil) {
        fullName = [fullName stringByAppendingString:firstName];
    }
    if (lastName != nil) {
        fullName = [fullName stringByAppendingString:@" "];
        fullName = [fullName stringByAppendingString:lastName];
    }

    tempArray = [[NSMutableArray alloc] init];
    [tempArray addObject:fullName];
    
    NSArray *phones = (NSArray *)ABMultiValueCopyArrayOfAllValues(ABRecordCopyValue(person, kABPersonPhoneProperty));
    NSArray *emails = (NSArray *)ABMultiValueCopyArrayOfAllValues(ABRecordCopyValue(person, kABPersonEmailProperty));
    
      // Make sure that the selected contact has one phone at least filled in.
    if ([phones count] > 0) {
            [tempArray addObject:[phones objectAtIndex:0]];
    }
    else{
        [tempArray addObject:@"No phone number was set."];
    }
    
    // Do the same for the e-mails.
    // Make sure that the selected contact has one email at least filled in.
    if ([emails count] > 0) {
        [tempArray addObject:[emails objectAtIndex:0]];
    }
    else{
        [tempArray addObject:@"No e-mail was set."];
    }
   
    txtName.text =[tempArray objectAtIndex:0];
    txtPhone.text =[tempArray objectAtIndex:1];
    txtEmail.text =[tempArray objectAtIndex:2];
    
    [tempArray release];
    [contacts dismissModalViewControllerAnimated:YES];
    [contacts release];
    
return YES;
}
-(void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker{
[contacts dismissModalViewControllerAnimated:YES];
[contacts release];
}


- (BOOL)validateEmailWithString:(NSString*)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end

AsyncImage


AsyncImage.h

#import <UIKit/UIKit.h>

#import "ASIHTTPRequest.h"
#import "CustomScrollBar.h"
#import <QuartzCore/QuartzCore.h>


@protocol AsyncImageDelegate

@optional
- (void) reSetFrame:(UIView *)newView;
@end

@interface AsyncImage : UIView<CustomScrollBarDelegate,UIScrollViewDelegate>
{
    NSURLConnection* connection; 
NSMutableData* data; 
UIImageView *image;
    UIImageView *imageView;
UIActivityIndicatorView *scrollingWheel;
    NSString *imgName;
    NSString *strImgurl;
    
    CGRect fullFrame;
    NSString *entryId;

    ASIHTTPRequest *request;
    CustomScrollBar *scroller;
    
    float heightNew;
    float imgWidth, imgHeight;
    
    NSObject<AsyncImageDelegate> *delegate;
}
@property(nonatomic,retain) NSString *entryId;
@property(nonatomic,retain)UIImageView *image;
@property(nonatomic,retain) NSURLConnection* connection;
@property (nonatomic, assign) NSObject<AsyncImageDelegate> *delegate;

-(void)loadImageFromString:(NSString*)url dict:(NSDictionary *)dict;
-(id) initWithFrame:(CGRect)frame;
-(NSString *)applicationDocumentsDirectory;
-(void)cancelConnection;
- (void)loadImageWhileSetObject:(NSString*)url;
-(float)getHeight : (UIImage *)img;
-(UIImage *)resizeImage:(UIImage *)image;
-(void)loadImageForVisibleCell:(NSString*)url dict:(NSDictionary *)dict;
@end

AsyncImage.m

#import "AsyncImage.h"
#import "FishbowlAppDelegate.h"

@implementation AsyncImage
FishbowlAppDelegate *appDelegate;

@synthesize entryId;
@synthesize image;
@synthesize connection;

@synthesize delegate;


- (id)initWithFrame:(CGRect)frame {
    if ((self = [super initWithFrame:frame])) {
        
       imageView = [[UIImageView alloc] init];
        
        appDelegate = [FishbowlAppDelegate sharedAppDelegate];

scroller = [[CustomScrollBar alloc] initWithFrame:frame];
        //         scroller = [[CustomScrollBar alloc] initWithFrame:CGRectMake(0, 0, 480, 320)];
scroller.maximumZoomScale = 4.0;
scroller.minimumZoomScale = 1.0;
scroller.clipsToBounds = YES;
// a page is the width of the scroll view
//scroller.backgroundColor = [UIColor redColor];
scroller.scrollEnabled = YES;
scroller.multipleTouchEnabled = YES;
scroller.userInteractionEnabled = YES;
scroller.showsHorizontalScrollIndicator = YES;
scroller.showsVerticalScrollIndicator = YES;
scroller.scrollsToTop = NO;
scroller.delegate = self;
scroller.del = self;
scroller.contentSize = frame.size;

  scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
float x = self.bounds.size.width/2;
float y = self.bounds.size.height/2;
scrollingWheel.center = CGPointMake(x, y);
scrollingWheel.hidesWhenStopped = YES;
       // [scroller addSubview:scrollingWheel];
       // self.clipsToBounds = YES;
        
[self addSubview:scrollingWheel];
        imageView.center = CGPointMake(x, y);
      //  [scroller addSubview:imageView];
        [self addSubview:scroller];
self.clipsToBounds = YES;
        
       // [scroller addSubview:imageView];
        }
    return self;
}
-(void)loadImageFromString:(NSString*)url dict:(NSDictionary *)dict;
{
    scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    float x = self.bounds.size.width/2;
    float y = self.bounds.size.height/2;
    scrollingWheel.center = CGPointMake(x, y);
    scrollingWheel.hidesWhenStopped = YES;
    [self addSubview:scrollingWheel];

  [scrollingWheel startAnimating];
if (connection!=nil) {
        [connection cancel];
[connection release];
        
connection = nil;
        
}
    
    if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}

    if(dict == nil)
    {
        imgName =[[[url componentsSeparatedByString:@"/"] lastObject]retain];
    }
    else
    {
         imgName =[NSString stringWithFormat:@"%@_%@",[[[url componentsSeparatedByString:@"/"] lastObject]retain],[dict objectForKey:@"FacebookId"]];
    
    }
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [imgName retain];
    
    NSFileManager *fileManager = [NSFileManager defaultManager]; 
    if ([fileManager fileExistsAtPath:imagePath]==NO)
    {
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
    
        NSURLRequest* urequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:urequest delegate:self];
    }
    else
    {
        UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
         [UIImage imageWithContentsOfFile:imagePath];
        
     //   image = [[[UIImageView alloc] initWithImage:img] autorelease];
        image =[[UIImageView alloc] initWithImage:img];
        image.contentMode = UIViewContentModeScaleAspectFit;
        image.frame = self.bounds;
         image.layer.cornerRadius =5.0f;
[self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}

-(void)loadImageForVisibleCell:(NSString*)url dict:(NSDictionary *)dict;
{
    scrollingWheel = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    float x = self.bounds.size.width/2;
    float y = self.bounds.size.height/2;
    scrollingWheel.center = CGPointMake(x, y);
    scrollingWheel.hidesWhenStopped = YES;
    [self addSubview:scrollingWheel];
    
  [scrollingWheel startAnimating];
if (connection!=nil) {
        [connection cancel];
[connection release];
        
connection = nil;
}
    
    if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
    
    if(dict == nil)
    {
        imgName =[[[url componentsSeparatedByString:@"/"] lastObject]retain];
    }
    else
    {
        imgName =[NSString stringWithFormat:@"%@_%@",[[[url componentsSeparatedByString:@"/"] lastObject]retain],[dict objectForKey:@"FacebookId"]];
        
    }
    NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [imgName retain];
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:imagePath]==NO)
    {
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
        
        NSURLRequest* urequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
connection = [[NSURLConnection alloc] initWithRequest:urequest delegate:self];
    }
    else
    {
        UIImage *img = [UIImage imageWithContentsOfFile:imagePath];
        [UIImage imageWithContentsOfFile:imagePath];
        
        //   image = [[[UIImageView alloc] initWithImage:img] autorelease];
        image =[[UIImageView alloc] initWithImage:img];
        image.contentMode = UIViewContentModeScaleAspectFit;
        image.frame = self.bounds;
        image.layer.cornerRadius =5.0f;
[self addSubview:image];
    [scrollingWheel stopAnimating];
    }
}
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    [data release]; 
data=nil;
    [scrollingWheel stopAnimating];
}
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
data = [[NSMutableData data] retain];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)dataObj {
[data appendData:dataObj];
}
- (void) connectionDidFinishLoading:(NSURLConnection *)theConnection 
{
[connection release];
connection=nil;

     NSString *imagePath = [[self applicationDocumentsDirectory] stringByAppendingPathComponent:imgName];
    
    [data writeToFile:imagePath atomically:YES];
    
image = [[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]] autorelease];
  //  image =[[UIImageView alloc] initWithImage:[UIImage imageWithData:data]];
image.contentMode = UIViewContentModeScaleToFill;
    [image setClipsToBounds:YES];
    
  image.frame = self.bounds;
[self addSubview:image];
    
[data release]; 
data=nil;
[scrollingWheel stopAnimating];
    [imgName release];
}
-(NSString *)applicationDocumentsDirectory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
return basePath;
}
-(void)cancelConnection{
    
    if (connection !=nil) {
        [connection cancel];
        connection=nil;
    }
    if(data!=nil){
        [data release]; 
        data=nil;
    }
    
[scrollingWheel stopAnimating];
}
-(void)asyncImageSet:(UIImage *)img
{
    [scrollingWheel startAnimating];
if (connection!=nil) {
[connection release];
connection = nil;
}
if (data!=nil) {
[data release];
data = nil;
}
if (image != nil) {
[image removeFromSuperview];
image = nil;
}
    
    image = [[[UIImageView alloc] initWithImage:img] autorelease];
image.contentMode = UIViewContentModeScaleToFill;
    [image setClipsToBounds:YES];
    
    image.frame = self.bounds;
    
    [self addSubview:image];
    [scrollingWheel stopAnimating];
}
#pragma mark -
#pragma mark scrollView Delegate Methods
-(UIView*)viewForZoomingInScrollView:(UIScrollView *)scrollView {
return image;
}
#pragma mark -
#pragma mark Touch Delegate Methods
- (void)touchesBeganScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesMovedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
}
- (void)touchesEndedScroll:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
if ([touch tapCount] == 1) {
        
        [scroller setZoomScale:1.0];
        
        [self setViewAnimation:CGRectMake(0,0, self.bounds.size.width, self.bounds.size.height)];
    }
}
-(void) setViewAnimation:(CGRect)frame {
[UIView beginAnimations:nil context:NULL];
[UIView setAnimationDuration:0.5];
    image.frame = self.frame;
    scroller.contentSize = self.frame.size;
    [UIView commitAnimations];
}

- (void)dealloc {
 //   [imgName release];
[scrollingWheel release];
    [super dealloc];
}
@end

Sunday, September 8, 2013

TabBar

TabBar.h


#import <UIKit/UIKit.h>

#define tabBarFrame CGRectMake(0, 768, 1024, 48)

@interface TabBarIphone : UITabBarController <UITabBarControllerDelegate, UITabBarDelegate> {
@public
UIView *view;

}
-(void)setFor:(NSString*)str;

- (void) loadBookContent;

-(void) addCustomElements;
-(void) selectTab:(int)tabID;


@end


#import "TabBarIphone.h"
#import <QuartzCore/QuartzCore.h>
#import "AppDelegate.h"

@implementation TabBarIphone
AppDelegate *appDelegate;

NSString *strForPurpose;
NSString *strAdd;

#pragma mark -
#pragma mark Custom Methods

/*-(void) onClickSave {
[appDelegate saveAction]; 
}*/

TabBar.m

#pragma mark -
#pragma mark Init Methods

-(id) init {
[super init];
    
appDelegate = (AppDelegate*)[UIApplication sharedApplication].delegate;

self.delegate = self;
self.customizableViewControllers = nil;
        
return self;
}

#pragma mark -
#pragma mark View Methods

- (void)viewDidLoad {
    
    [super viewDidLoad];
self.navigationController.navigationBar.hidden = FALSE;
    
    self.tabBar.backgroundColor = [UIColor whiteColor];
}
- (void)viewWillAppear:(BOOL)animated {
    
[super viewWillAppear:animated];
[self tabBar].hidden = FALSE;
}
-(void)setFor:(NSString*)str {
strAdd=str;
}
- (BOOL)tabBarController:(UITabBarController *)tabBarController 
shouldSelectViewController:(UIViewController *)viewController {
//NSLog(@"didSelectItem:(UITabBarItem *)item  %@ ",viewController);
     return TRUE;
}
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    [appDelegate.navHome popToRootViewControllerAnimated:YES];
    [appDelegate.navNotes popToRootViewControllerAnimated:YES];
    [appDelegate.navUpload popToRootViewControllerAnimated:YES];
    [appDelegate.navResearch popToRootViewControllerAnimated:YES];
    [appDelegate.navForum popToRootViewControllerAnimated:YES];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
if (buttonIndex == 0) {
[self setSelectedIndex:0];
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark -
#pragma mark Memory Management
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

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