Friday, 24 July 2015

Image to Byte and Byte to Image conversion

In many situations we need to convert image to byte. It is useful in many scenarios because byte arrays can be easily compared, compressed, stored, or converted to other data types.
Here a simple code to convert image to byte array.

//Using image picker for select a image(we can use any specified way for selecting a image).

-(IBAction)openPhotoAlbum:(UIButton *)sender{
    UIImagePickerController *pickerController = [[UIImagePickerController alloc] init];
    pickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    pickerController.delegate = self;
    [self presentViewController:pickerController animated:YES completion:nil];
}
-(void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    [picker dismissViewControllerAnimated:YES completion:nil];
    // Get selected image
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self
convertImageToByte: image];
}
-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:nil];
}


//Convert image to byte format
-(void) convertImageToByte:(UIImage *)image{
       NSData *data = UIImagePNGRepresentation(image);
       NSUInteger len = data.length;
       uint8_t *bytes = (uint8_t *)[data bytes];
      NSMutableString *result = [NSMutableString stringWithCapacity:len * 3];
       for (NSUInteger i = 0; i < len; i++) {
        if (i) {
            [result appendString:@","];
        }
        [result appendFormat:@"%d", bytes[i]];
    }
    [result appendString:@"]"];
    NSLog(@"Image in Byte  = %@",result);

}  


//Change byte to UIImage
-(void)convierteImagen: (NSMutableString *)cadenaImagen{
   
    NSArray *strings = [cadenaImagen componentsSeparatedByString:@","];
    unsigned c = strings.count;
    uint8_t *bytes = malloc(sizeof(*bytes) * c);
   
    unsigned i;
    for (i = 0; i < c; i++)
    {
        NSString *str = [strings objectAtIndex:i];
        int byte = [str intValue];
        bytes[i] = (uint8_t)byte;
    }
   
    NSData *data = [NSData dataWithBytes:bytes length:c];

    //get image
    UIImage *image = [UIImage imageWithData:data];
    //Display image on UIImageView
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 400,   400)];
    imageView.image = image;
    [self.view addSubview:imageView];
}

Friday, 17 July 2015

Post Request in Swift

One of the very useful functionality and frequent used for mobile application development, if application interact with server.

Most of the application communicate with server over HTTP Post request.

In this blog you can see how to communicate with server over HTTP Post method.


 func postRequestToServer(postUrl:NSString, postParameters:NSDictionary) {     
        var url = NSURL(string: postUrl)
        var postData:NSData!
        postData = NSJSONSerialization.dataWithJSONObject(postParameters, options:                NSJSONWritingOptions.PrettyPrinted, error: nil)
       
        var request = NSMutableURLRequest(URL: url!, cachePolicy: NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData, timeoutInterval: 50)
        var postDataLength = NSString(format: "%lu", postData.length)
       
        request.setValue(postDataLength, forHTTPHeaderField: "Content-Length")
        request.HTTPBody = postData
        request.HTTPMethod = "POST"
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
        request.setValue("application/json", forHTTPHeaderField: "Accept")
        var urlResponse : NSURLResponse?
        var error : NSError?
        var responseData : NSData!
        responseData = NSURLConnection.sendSynchronousRequest(request, returningResponse: &urlResponse, error: &error)
       
        var returnDict:NSDictionary? = nil
       
        if responseData==nil{
            println("Nil Response")
            return
        }
       
        var parseResponse: AnyObject? = NSJSONSerialization.JSONObjectWithData(responseData, options: NSJSONReadingOptions.MutableLeaves, error: nil)
       
        if (parseResponse?.isKindOfClass(NSDictionary) != nil){
            NSLog("parse response = %@", parseResponse as NSDictionary)
        }
        else if ((parseResponse?.isKindOfClass(NSArray)) != nil){
            NSLog("parse response = %@", parseResponse as NSArray)
         }
       }//End method

Friday, 10 July 2015

Core Animation

Core Animation is a graphics rendering and animation infrastructure use to animate the views and other visual elements. Core Animation is not a replacement for app’s views. Instead, it is a technology that integrates with views to provide better performance and support for animating their content. All you have to do is configure a few animation parameters (such as the start and end points) and tell Core Animation to start. Core Animation does the rest, handing most of the actual drawing work off to the onboard graphics hardware to accelerate the rendering. This automatic graphics acceleration results in high frame rates and smooth animations without burdening the CPU and slowing down your app.

Below code add "Pulse Effect" animation.

//Create a CALayer
CALayer *animatelayer = [CALayer layer];
//Setting Frame for CALayer
animatelayer.frame = CGRectMake(0,0, 160, 160);
//Setting Color for CALayer
animatelayer.backgroundColor = [UIColor redColor].CGColor;
//Setting Position for CALayer
animatelayer.position = (CGPoint){CGRectGetMidX(self.view.bounds), CGRectGetMidY(self.view.bounds)};
//Setting Corner radius for CALayer to look like a Circle
animatelayer.cornerRadius = 80;

//Create a Basic Animation
CABasicAnimation *theAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
theAnimation.duration=2.0;
theAnimation.repeatCount=HUGE_VALF;
theAnimation.autoreverses=YES;theAnimation.fromValue=[NSNumber numberWithFloat:0.7];
theAnimation.toValue=[NSNumber numberWithFloat:0.0];

//Add animation to CALayer
[animatelayer addAnimation:theAnimation forKey:@"animateOpacity"];

//Add CALayer to View
[self.view.layer insertSublayer:animatelayer atIndex:0];

For details Click here

Friday, 3 July 2015

NSOperation and NSOperationQueue



The NSOperationQueue class regulates the execution of a set of NSOperation objects. After being added to a queue, an operation remains in that queue until it is explicitly canceled or finishes executing its task. Operations within the queue (but not yet executing) are themselves organized according to priority levels and inter-operation object dependencies and are executed accordingly. An application may create multiple operation queues and submit operations to any of them. 

Inter-operation dependencies provide an absolute execution order for operations, even if those operations are located in different operation queues. An operation object is not considered ready to execute until all of its dependent operations have finished executing.

You cannot directly remove an operation from a queue after it has been added. An operation remains in its queue until it reports that it is finished with its task. Finishing its task does not necessarily mean that the operation performed that task to completion. An operation can also be canceled. Canceling an operation object leaves the object in the queue but notifies the object that it should abort its task as quickly as possible. 

Operation queues usually provide the threads used to run their operations. Operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations. As a result, operations are always executed on a separate thread, regardless of whether they are designated as asynchronous or synchronous operations.

Implementation of NSOperation:
1.) Create sub-class of NSOperation

Sample Code:

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

@protocol DownloadOperationDelegate; // Declare delegate

@interface DownloadOperation : NSOperation
@property (nonatomic, strong) NSString *urlstring;   // declare a NSString variable
@property (nonatomic, weak) id <DownloadOperationDelegate> delegate;
-(instancetype) initWithUrlString:(NSString *)urlString andDelegate:(id<DownloadOperationDelegate>) delegate;  // Declare  a method for initialize new instance.
@end

@protocol DownloadOperationDelegate <NSObject>
//Delegate method
-(void) downloadOperation:(DownloadOperation *)operation finishedWithData:(id)result;
-(void) downloadOperation:(DownloadOperation *)operation finishedWithError:(NSError *)error;
@end

#import "DownloadOperation.h"

@implementation DownloadOperation
-(instancetype) initWithUrlString:(NSString *)urlString andDelegate:(id<DownloadOperationDelegate>)delegate{
   
    self = [super init];
    if (self != nil) {
        self.urlstring = urlString;
        self.delegate = delegate;
    }
    return self;
}

-(void) main{
    @autoreleasepool {

        if (self.cancelled) {   //return No if you cancel queue operation.
            return;
        }
        //--------------
        /*
        
             Add Code Here
        
         */
        /*
        
              After completion of define task you can notifiy by delegate method.
         if get error:
         NSError *error;
         if (error) {
         if (self.delegate && [self.delegate respondsToSelector:@selector(downloadOperation:finishedWithError:)]) {
         [self.delegate downloadOperation:self finishedWithError:error];
         }
         }
        
         Notify Task completion:
         id resultData;
         if (self.delegate && [self.delegate respondsToSelector:@selector(downloadOperation:finishedWithData:)]) {
         [self.delegate downloadOperation:self finishedWithData:resultData];
         }
        
         */
       
    }
}
@end



NOTE: Add task inside auto-release pool.

2.) Create new instance of NSOperation:
DownloadOperation *operation = [[DownloadOperation alloc] initWithUrlString:@"" andDelegate:self];

3.) Add newly created NSOperation's instance to NSOperationQueue:

NSOperationQueue *downloadQueue = [[NSOperationQueue alloc] init];//Create a instance of    NSOpearionQueue
downloadQueue.name = @"Download Database"; // Set name for created NSOperarionQueue.
downloadQueue.maxConcurrentOperationCount = 5; // Set maximum number of operations can run concurrently.
[downloadQueue addOperation:operation];//Add Operation to Operation Queue.

NOTE: You can add multiple NSOperations inside single NSOperationQueue, so no need to create multiple instance for NSOperationQueue. Just create instance of NSOperations and add inside NSOperationQueue's instance.

You can cancel ALL QUEUE OPERATIONS by:
[downloadQueue cancelAllOperations];

FOR DETAILS CLICK HERE