Showing posts with label ios. Show all posts
Showing posts with label ios. Show all posts

Sunday, 11 January 2015

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

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

Thumbnail from video- iOS


UIImageView*img=[[UIImageView alloc]initWithFrame:CGRectMake(140, -40, 200, 200)];
            AVURLAsset *asset1 = [[AVURLAsset alloc] initWithURL:msg.mediaURL options:nil];
            AVAssetImageGenerator *generate1 = [[AVAssetImageGenerator alloc] initWithAsset:asset1];
            generate1.appliesPreferredTrackTransform = YES;
            NSError *err = NULL;
            CMTime time = CMTimeMake(1, 2);
            CGImageRef oneRef = [generate1 copyCGImageAtTime:time actualTime:NULL error:&err];
            UIImage *one = [[UIImage alloc] initWithCGImage:oneRef];
            [img setImage:one];
            img.contentMode = UIViewContentModeScaleAspectFit;

Get IP Address -iOS Development


#include <ifaddrs.h>
#include <arpa/inet.h>

- (NSString *)getIPAddress {
    
    struct ifaddrs *interfaces = NULL;
    struct ifaddrs *temp_addr = NULL;
    NSString *wifiAddress = nil;
    NSString *cellAddress = nil;
    
    // retrieve the current interfaces - returns 0 on success
    if(!getifaddrs(&interfaces)) {
        // Loop through linked list of interfaces
        temp_addr = interfaces;
        while(temp_addr != NULL) {
            sa_family_t sa_type = temp_addr->ifa_addr->sa_family;
            if(sa_type == AF_INET || sa_type == AF_INET6) {
                NSString *name = [NSString stringWithUTF8String:temp_addr->ifa_name];
                NSString *addr = [NSString stringWithUTF8String:inet_ntoa(((struct sockaddr_in *)temp_addr->ifa_addr)->sin_addr)]; // pdp_ip0
                NSLog(@"NAME: \"%@\" addr: %@", name, addr); // see for yourself
                
                if([name isEqualToString:@"en0"]) {
                    // Interface is the wifi connection on the iPhone
                    wifiAddress = addr;
                } else
                    if([name isEqualToString:@"pdp_ip0"]) {
                        // Interface is the cell connection on the iPhone
                        cellAddress = addr;
                    }
            }
            temp_addr = temp_addr->ifa_next;
        }
        // Free memory
        freeifaddrs(interfaces);
    }
    NSString *addr = wifiAddress ? wifiAddress : cellAddress;
    return addr ? addr : @"0.0.0.0";
    
}

Thursday, 8 January 2015

iOS 8 App Extensions- dlopen() Loading Embeded framework at runtime

Unlink Your Embeded framework from Project Target


#import <dlfcn.h>

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
 
NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    if ([currSysVer  floatValue]>=8.0) {
        [self loadFrameworkDynamic];
    }
   
  return YES;
}

- (void)loadFrameworkDynamic
{
//WidgetSource is the name of framework
    NSString *LibName = @"WidgetSource";
    NSString *LibExtension = @"framework";
    NSString *Path = [[NSBundle mainBundle] pathForResource:LibName ofType:LibExtension];
    NSLog(@"Loading dynamic library: %@", Path);
    Path=[Path stringByAppendingString:@"/WidgetSource"];
  
    void *revealLib = NULL;
    revealLib = dlopen([Path cStringUsingEncoding:NSUTF8StringEncoding], RTLD_NOW);
   
    if (revealLib == NULL)
    {
        char *error = dlerror();
        NSLog(@"dlopen error: %s", error);
        NSString *message = [NSString stringWithFormat:@"%@.%@ failed to load with error: %s", LibName, LibExtension, error];
        [[[UIAlertView alloc] initWithTitle:@"Library could not be loaded" message:message delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil] show];
    }
}