Powered By Blogger

Friday, July 13, 2012

how to compress string according to frame in iphone sdk?

Hi everyone,
Please check the below tip for Compression of string according to your view/controller frame size.
 
        UILabel *lable =[[UILabel alloc]initWithFrame:CGRectMake(X_POS, Y_POS, width, height)];
        lable.tag = tag;
        lable.backgroundColor = [UIColor clearColor];
        lable.lineBreakMode = UILineBreakModeWordWrap;
        lable.numberOfLines = 10.0;


            CGFloat fontHeight = 15.0;
            BOOL huge = YES;
            while (huge)
            {
                CGSize boundingSize = CGSizeMake(lable.frame.size.width, CGFLOAT_MAX);
                CGSize requiredSize = [lable.text sizeWithFont:lable.font
                                             constrainedToSize:boundingSize
                                                 lineBreakMode:UILineBreakModeWordWrap];
                NSLog(@"Width:%f",requiredSize.width) ;
                NSLog(@"Height:%f",requiredSize.height) ;
                NSLog(@"NumberofLines : %f",requiredSize.height/lable.font.lineHeight);
               
                if (lable.frame.size.height<requiredSize.height)
                {
                    fontHeight --;
                    lable.font = [UIFont fontWithName:@"Verdana" size:fontHeight];
                    lable.adjustsFontSizeToFitWidth = YES;
                }
                else
                {
                    huge = NO;
                }
            }

Thanks & Regards,
Nilesh Prajapati

Tuesday, July 10, 2012

How to fetch documents from Directory in iPhone?

Hi,
Here is the tricky code for fetching document list from Directory in iPhone/iPad/iOS Application. Here, I have used code to delete all documents from My Application Document directory.

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
       
        NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL]; 
        NSEnumerator *e = [contents objectEnumerator];
        NSString *filename;
        while ((filename = [e nextObject])) {
            [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:nil];
        }


Thanks & Regards,
Nilesh Prajapati

lazy loading in iphone

Hi,
Here I'm placing code for LazyLoading of Images in iPhone/iPad/iOS Application. Please go through it. It'll surely help you.

Step 1: Create  "DTLazyImageView.h"

@class DTLazyImageView;

@protocol DTLazyImageViewDelegate <NSObject>
@optional
- (void)lazyImageView:(DTLazyImageView *)lazyImageView didChangeImageSize:(CGSize)size;
- (void)imageDidLoad: (DTLazyImageView *) lazyImageView;
@end

@interface DTLazyImageView : UIImageView
{
    UIActivityIndicatorView *actv;
}
@property (nonatomic, strong) NSURL *url;
@property (nonatomic, assign) BOOL shouldShowProgressiveDownload;
@property (nonatomic, strong) UIActivityIndicatorView *actv;
@property (nonatomic, assign) id<DTLazyImageViewDelegate> delegate;    // subtle simulator bug - use assign not __unsafe_unretained

- (void)startLoading;
- (void)cancelLoading;
- (void)loadImageAtURL:(NSURL *)url;
@end

Step 2: Create  "DTLazyImageView.m" file.


#import "DTLazyImageView.h"

static NSCache *_imageCache = nil;

@interface DTLazyImageView ()

- (void)notify;

@end

@implementation DTLazyImageView
{
    NSURL *_url;
   
    NSURLConnection *_connection;
    NSMutableData *_receivedData;

    CGFloat _fullHeight;
    CGFloat _fullWidth;
    NSUInteger _expectedSize;
   
    BOOL shouldShowProgressiveDownload;
   
    __unsafe_unretained id<DTLazyImageViewDelegate> _delegate;
}
@synthesize delegate=_delegate;

- (void)dealloc
{   
    [_connection cancel];
    actv = nil;
}

- (void) startLoading
{
    NSLog(@"Tag: %d , Url :%@",self.tag,[_url absoluteString]);
   
    if (!self.image && [[_url absoluteString] length]>0)
    {
        UIImage *image = [_imageCache objectForKey:_url];
        actv = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        actv.frame = CGRectMake(50.0, 50.0, 20.0, 20.0);
        [self addSubview:actv];
        if (image)
        {
            self.image = image;
            _fullWidth = image.size.width;
            _fullHeight = image.size.height;
           
            // for unknown reasons direct notify does not work below iOS 5
            [self performSelector:@selector(notify) withObject:nil afterDelay:0.0];
            return;
        }
        [self loadImageAtURL:_url];
    }   
    else
    {
       UIImage *image = [UIImage imageNamed:@"logo.png"];
       self.image = image;
        _fullWidth = image.size.width;
        _fullHeight = image.size.height;
    }
}

- (void)loadImageAtURL:(NSURL *)url
{
    [self performSelectorInBackground:@selector(loadImage:) withObject:url];
}

- (void)loadImage:(NSURL *)url
{
    @autoreleasepool
    {
        [actv startAnimating];
        NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:60.0];
       
        _connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
        [_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
        [_connection start];
       
        // necessary because otherwise otherwise the delegate methods would not get delivered
        CFRunLoopRun();
    }
}


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

- (void)cancelLoading
{
    [_connection cancel];
    _connection = nil;
    _receivedData = nil;
}

#pragma mark NSURL Loading

- (void)notify
{
    [self.delegate imageDidLoad:self];
}

- (void)completeDownloadWithData:(NSData *)data
{
    UIImage *image = [[UIImage alloc] initWithData:data];
    self.image = image;
    _fullWidth = image.size.width;
    _fullHeight = image.size.height;
   
    [self notify];
    [actv stopAnimating];
    [actv removeFromSuperview];
   
    static dispatch_once_t predicate;
   
    dispatch_once(&predicate, ^{
        _imageCache = [[NSCache alloc] init];
    });
   
    if (_url)
    {
        // cache image
        [_imageCache setObject:image forKey:_url];
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // every time we get an response it might be a forward, so we discard what data we have
    _receivedData = nil;
   
    // does not fire for local file URLs
    if ([response isKindOfClass:[NSHTTPURLResponse class]])
    {
        NSHTTPURLResponse *httpResponse = (id)response;
       
        if (![[httpResponse MIMEType] hasPrefix:@"image"])
        {
            [self cancelLoading];
            return;
        }
    }
   
    /* For progressive download */
    _fullWidth = _fullHeight = -1.0f;
    _expectedSize = (NSUInteger)[response expectedContentLength];
   
    _receivedData = [[NSMutableData alloc] init];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_receivedData appendData:data];
}

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

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    if (_receivedData)
    {
        [self performSelectorOnMainThread:@selector(completeDownloadWithData:) withObject:_receivedData waitUntilDone:YES];
        _receivedData = nil;
    }
    _connection = nil;
    CFRunLoopStop(CFRunLoopGetCurrent());
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    _connection = nil;
    _receivedData = nil;
    CFRunLoopStop(CFRunLoopGetCurrent());
}

#pragma mark Properties

@synthesize url = _url;
@synthesize shouldShowProgressiveDownload;
@synthesize actv;
@end

Step 3:  DO the following steps to your current controller where you want to use LazyImageLoad.

#import "DTLazyImageView.h"

@interface RootViewController : UIViewController<DTLazyImageViewDelegate> {
   
    DTLazyImageView *lazyImageView;
}

@end

@implementation RootViewController

-(void)viewWillAppear:(BOOL)animated
{
    for(int i=0;i<5;i++)
    {
                DTLazyImageView *lazyImageView = [[DTLazyImageView alloc] init];
                lazyImageView.delegate = self;
                lazyImageView.tag = i;
                lazyImageView.frame = CGRectMake(x, y,width, height);
                lazyImageView.url = [NSURL URLWithString:@"put image url here"];
                [self.view addSubview:lazyImageView];
                if (! lazyImageView.image) {
                    [lazyImageView startLoading];
                }
    }

}

#pragma mark -
#pragma mark DTLazyImageView Delegate Method

- (void)imageDidLoad: (DTLazyImageView *) lazyImageView
{
    // place your custom code here
}

@end


Note : Using above steps you can easily, implement LazyLoad of images to your application.


Feel free to ask, if any Query.


Thanks & Regards,
Nilesh Prajapati

Thursday, July 5, 2012

how to draw images to PDF in iPhone sdk?

Hello friends,
I'm going to place PDF creation code for iOS SDK including images and textdraw. For this, you have to include "QuartzCore.framework" into your project.

Step 1: Include "QuartzCore.framework".

Step 2: Import "<QuartzCore/QuartzCore.h>" into your controller header file.

Step 3: Place below code into your class where you want to use it. You can change the parameters in your methods as per your requirement. You may change it any of the object.(Ex. UIView, UIImageView, etc...)


#pragma mark -
#pragma mark PDF Generation Code


-(IBAction)drawPdf:(id)sender
{
    [self writeImage:ImageView1 :1];
    [self writeImage:ImageView2 :2];
    [self writeImage:ImageView3 :3];
    [self drawImagesToPdf:ImageView1];
}


-(void)writeImage:(UIImageView *)btn:(NSInteger)tag
{
    CGRect screenRect = btn.frame;
    UIGraphicsBeginImageContext(screenRect.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    [[UIColor whiteColor] set];
    CGContextFillRect(ctx, screenRect);
    [btn.layer renderInContext:ctx];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
   
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png",tag]];
   
    [UIImagePNGRepresentation(newImage) writeToFile:pngPath atomically:YES];
}

-(void)drawImagesToPdf:(UIImageView *)button
{
CGSize pageSize = CGSizeMake(button.frame.size.width, button.frame.size.height*3+30);
  
    NSString *fileName = @"Demo.pdf";
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *pdfFileName = [documentsDirectory stringByAppendingPathComponent:fileName];
    UIGraphicsBeginPDFContextToFile(pdfFileName, CGRectMake(0, 0, button.frame.size.width, button.frame.size.height*3), nil);
  
    UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, 0.0, pageSize.width, button.frame.size.height), nil);
  
    NSString *name  = [NSString stringWithFormat:@"Unknown User];
    NSString *email = @"unknwon.hotmail.com";
    NSString *city=@"unknown";
    NSString *zip=@"unknown";
  
    [name drawInRect:CGRectMake(50.0, 50.0, button.frame.size.width-50.0, 20.0) withFont:[UIFont fontWithName:@"Verdana" size:15.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
  
    [email drawInRect:CGRectMake(50.0, 75.0, button.frame.size.width-50.0, 20.0) withFont:[UIFont fontWithName:@"Verdana" size:13.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
  
    [city drawInRect:CGRectMake(50.0, 100.0, button.frame.size.width-50.0, 20.0) withFont:[UIFont fontWithName:@"Verdana" size:13.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];

    [zip drawInRect:CGRectMake(50.0, 125.0, button.frame.size.width-50.0, 20.0) withFont:[UIFont fontWithName:@"Verdana" size:13.0] lineBreakMode:UILineBreakModeWordWrap alignment:UITextAlignmentLeft];
  
    for (int i =1; i<=3; i++)
    {
        double currentHeight = 0.0;
        UIGraphicsBeginPDFPageWithInfo(CGRectMake(0, currentHeight, pageSize.width, button.frame.size.height), nil);
        NSString *pngPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%d.png", i]];
        UIImage *pngImage = [UIImage imageWithContentsOfFile:pngPath];
        [pngImage drawInRect:CGRectMake(0, currentHeight, pageSize.width, pngImage.size.height)];
    }
    UIGraphicsEndPDFContext();}

Feel free to ask if you have any issue using this code. 

Thanks & Regards,
Nilesh Prajapati

Monday, July 2, 2012

UIPickerView Datasource and Delegate methods

Hello friends ,
I'm going to share the UIPIckerView's Datasource and Delegate methods. If you want to implement these methods in to your code then you have to place "<UIPickerViewDatasource,UIPickerViewDelegate>" into your header part of the file.

@protocol UIPickerViewDataSource<NSObject>
@required

// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView;

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component;
@end


@protocol UIPickerViewDelegate<NSObject>
@optional

// returns width of column and height of row for each component.
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component;
- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component;

// these methods return either a plain UIString, or a view (e.g UILabel) to display the row for the component.
// for the view versions, we cache any hidden and thus unused views and pass them back for reuse.
// If you return back a different object, the old one will be released. the view will be centered in the row rect 
- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component;
- (UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view;

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component;

@end