Sunday, 11 January 2015

iOS-Convert UIImage to Byte Array and vice versa



 //Convert UIImage to Byte Array


UIImage*imageOBJ;
if (imageOBJ) {       

 NSData *data = UIImagePNGRepresentation([[assist shared] getTranferImage]);

NSUInteger len = data.length;
        uint8_t *bytes = (uint8_t *)[data bytes];NSMutableString *result1 = [NSMutableString  stringWithCapacity:len * 3];

        for (NSUInteger i = 0; i < len; i++) {
            if (i) {
                [result1 appendString:@","];
            }
            [result1 appendFormat:@"%d", bytes[i]];
        }
       
        NSArray*arr=[result1 componentsSeparatedByString:@","];
        [dictnew setObject:arr forKey:@"Picture"];
    }

 //Convert Byte Array to UIImage

 NSArray* bytedata = [self.trans valueForKey:@"Picture"];
        unsigned c = bytedata.count;
        uint8_t *bytes = malloc(sizeof(*bytes) * c);
       
        unsigned i;
        for (i = 0; i < c; i++)
        {
            NSString *str = [bytedata objectAtIndex:i];
            int byte = [str intValue];
            bytes[i] = (uint8_t)byte;
        }
       
        NSData *datos = [NSData dataWithBytes:bytes length:c];
       
        imgTran=[[UIImageView alloc]initWithFrame:CGRectMake(5, 240, 150, 160)];
        [imgTran setImage:[UIImage imageWithData:datos]];  


iOS-Convert UIImage to Base64 and vice versa

- (void)viewDidLoad
{
// Do any additional setup after loading the view, typically from a nib.
    /*
     CONVERT BASE64 TO IMAGE
     */

    //Base64 image URL as string
    NSString *base64Url = @"https://dl.dropbox.com/u/37581115/base64image";

    //convert base64 url string to NSURL object
    NSURL *url = [NSURL URLWithString:base64Url];

    //fetch data from url in case if image is in utf8 format
    NSString *base64Image = [NSString stringWithContentsOfURL:url];
    
    //convert base64image to NSURL object
    url = [NSURL URLWithString:base64Image];
    
    //convert it to NSData object
    NSData *rawImageData = [NSData dataWithContentsOfURL:url];

    /*
    //SAVE TO DISK
    NSString  *jpgPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"]; // identity the home directory and file name
    [rawImageData writeToFile:jpgPath atomically:YES];
    */

    /*
     CHECK DATA TYPE OF IMAGE FILE FROM NSData
     NSString * imageExt = [self contentTypeForImageData:rawImageData];
     */

    //convert NSData to UIImage object
    UIImage *image = [UIImage imageWithData:rawImageData];

    //Set image to uiview
    imageView.image = image;

    /*
     CONVERT IMAGE TO BASE64
     */

    //Reconvert UIImage to NSData
    NSData *imageData = UIImageJPEGRepresentation(image, 1.0);

    //And then apply Base64 encoding to convert it into a base-64 encoded string:
    NSString *encodedString = [self base64forData:imageData];

    //NSLog(@"encodedString is %@",encodedString);
    //Show in UITextView
    textView.text = encodedString;

}

- (NSString *)contentTypeForImageData:(NSData *)data {
    uint8_t c;
    [data getBytes:&c length:1];
    
    switch (c) {
        case 0xFF:
            return @"image/jpeg";
        case 0x89:
            return @"image/png";
        case 0x47:
            return @"image/gif";
        case 0x49:
        case 0x4D:
            return @"image/tiff";
    }
    return nil;
}

- (NSString*)base64forData:(NSData*)theData {
    
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];
    
    static char table[] ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    
    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;
    
    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;
            
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
} 

iOS-Placeholder in TextView


 Create a new file to Extend UITextView class




 //Copy this code in h file
 //h file
#import <UIKit/UIKit.h>
@interface PlaceholderTextView : UITextView
{
    UILabel *_placeholderLabel;
}


@property (strong, nonatomic) NSString *placeholderText;
@property (strong, nonatomic) UIColor *placeholderColor;


@end


 //Copy this code in m file
//m file
#import "PlaceholderTextView.h"


@implementation PlaceholderTextView


#pragma mark - init & dealloc


- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self)
    {
        [self initialize];
    }
   
    return self;
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self)
    {
        [self initialize];
    }
   
    return self;
}


- (id)init
{
    self = [super init];
    if (self)
    {
        [self initialize];
    }
   
    return self;
}


- (void)initialize
{
    _placeholderColor = [UIColor lightGrayColor];
    [self layoutGUI];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged:) name:UITextViewTextDidChangeNotification object:self];
}


- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


#pragma mark - Notification center


- (void)textChanged:(NSNotification *)notification
{
    if (notification.object == self)
        [self layoutGUI];
}


#pragma mark - layoutGUI


- (void)layoutGUI
{
    _placeholderLabel.alpha = [self.text length] > 0 || [_placeholderText length] == 0 ? 0 : 1;
}


#pragma mark - Setters


- (void)setText:(NSString *)text
{
    [super setText:text];
    [self layoutGUI];
}


- (void)setPlaceholderText:(NSString*)placeholderText
{
    _placeholderText = placeholderText;
    [self setNeedsDisplay];
}


- (void)setPlaceholderColor:(UIColor*)color
{
    _placeholderColor = color;
    [self setNeedsDisplay];
}


#pragma mark - drawRect


- (void)drawRect:(CGRect)rect
{
    if ([_placeholderText length] > 0)
    {
        if (!_placeholderLabel)
        {
            _placeholderLabel = [[UILabel alloc] initWithFrame:CGRectMake(8, 8, self.bounds.size.width - 16, 0)];
            _placeholderLabel.lineBreakMode = NSLineBreakByWordWrapping;
            _placeholderLabel.numberOfLines = 0;
            _placeholderLabel.font = self.font;
            _placeholderLabel.backgroundColor = [UIColor clearColor];
            _placeholderLabel.alpha = 0;
            [self addSubview:_placeholderLabel];
        }
       
        _placeholderLabel.text = _placeholderText;
        _placeholderLabel.textColor = _placeholderColor;
        [_placeholderLabel sizeToFit];
        [self sendSubviewToBack:_placeholderLabel];
    }
   
    [self layoutGUI];
   
    [super drawRect:rect];
}


// How to use
 Select TextView then go to inspector Panel as you can see in the following  Image and Enter Custom TextView Class Name 
"PlaceholderTextView"
Next Step is to set Outlet for the textView in drag-n drop way.

Import Class  
#import "PlaceholderTextView.h"

@interface Create ()
@property (strong, nonatomic) IBOutlet PlaceholderTextView *notes;

@end

- (void)viewDidLoad {
    [super viewDidLoad];
    self.notes.placeholderText=@"Notes";
    self.notes.layer.borderWidth=1;
    self.notes.layer.borderColor=[[UIColor blackColor]CGColor];
    // Do any additional setup after loading the view from its nib.
}

Friday, 9 January 2015

iOS-Get Date time from Time Stamp



NSString*betweenBraces,*newString;
NSRange start = [[dict valueForKey:@"DateCreated"] rangeOfString:@"("];
   NSRange  end = [[dict valueForKey:@"DateCreated"] rangeOfString:@")"];
  

 if (start.location != NSNotFound && end.location != NSNotFound && end.location ]] >  start.location)
    {
        betweenBraces = [[dict valueForKey:@"DateCreated"] substringWithRange:NSMakeRange(start.location+1, end.location-(start.location+1))];
    }
    newString = [betweenBraces substringToIndex:[betweenBraces length]-8];
      NSTimeInterval _interval=[newString doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *_formatter=[[NSDateFormatter alloc]init];
    [_formatter setDateFormat:@"dd/MM/yyyy"];
    NSString *_date=[_formatter stringFromDate:date];
    UILabel *datelbl = [UILabel new];
    [datelbl setText:_date];
   [self.view addSubView:
datelbl];

force an iPhone user to upgrade an application





Get Version info Using Itunes web service 
   NSURL *url = [NSURL URLWithString:@"http://itunes.apple.com/lookup?id=<Your app ID>"]; versionRequest = [ASIFormDataRequest requestWithURL:url]; versionRequest setRequestMethod:@"GET"];  versionRequest setDelegate:self]; versionRequest setTimeOutSeconds:100]; [versionRequest addRequestHeader:@"Content-Type" value:@"application/json"];  [versionRequest startSynchronous];
 
Response string of our REST call 
 



NSString* jsonResponseString = [versionRequest responseString]; NSDictionary *loginAuthenticationResponse = [jsonResponseString objectFromJSONString]; NSArray *configData = [loginAuthenticationResponse valueForKey:@"results"]; for (id config in configData) {
    version = [config valueForKey:@"version"];
     }

 

Compare Both Versions  

NSString *version = @"1.0"; if (![version isEqualToString:[itsUserDefaults objectForKey:@"version"]])  {
    UIAlertView *createUserResponseAlert = [[UIAlertView alloc] initWithTitle:@"New Version!!" message: @"A new version of app is available to download" delegate:selfcancelButtonTitle:nil otherButtonTitles: @”Update", nil];
    [createUserResponseAlert show]; 
    [createUserResponseAlert release];//Avoid if using Automatic reference counting }
Redirect User
-(void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSString *iTunesLink = @"itms-apps://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftwareUpdate?id=<appid>&mt=8";
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]]; }