Friday, 21 August 2015

Copy Table From One Database to another Database

SQLite is a powerful relational database used for storing data in iOS Applications.

Here code for, Copy table from one database to  another database.

-(void) createCopyDatabase{

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES);
    NSString *documentsDir = [paths objectAtIndex:0];
    
 //Get path for Source Database
    NSString *maindbPath = [documentsDir stringByAppendingPathComponent:@"User.sqlite"];;
    
 //Path for new Database
    NSString *newdbPath = [documentsDir stringByAppendingPathComponent:@"User_copy.sqlite"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    char *error;

//Remove previously existing file
    if ([fileManager fileExistsAtPath:newdbPath]) {
        [fileManager removeItemAtPath:newdbPath error:nil];
    }
    sqlite3 *database;
    //open database
    if (sqlite3_open([newdbPath UTF8String], &database)!=SQLITE_OK) {
        NSLog(@"Error to open database");
    }
//Query for Attach both Database
    NSString *attachQuery = [NSString stringWithFormat:@"ATTACH DATABASE \"%@\" AS existingDB",maindbPath];
   
    sqlite3_exec(database, [attachQuery UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to Attach = %s",error);
    }
//Query for copy Table
    NSString *sqlString = @"CREATE TABLE Info AS SELECT * FROM
existingDB.Info";     
    sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to copy database = %s",error);
    }
   
    //Query for copy Table with Where Clause
    sqlString = @"CREATE TABLE comments AS SELECT * FROM
existingDB.comments Where user_name = 'XYZ'";
    sqlite3_exec(database, [sqlString UTF8String], NULL, NULL, &error);
    if (error) {
        NSLog(@"Error to copy database = %s",error); 
       
    }
   
}

Friday, 7 August 2015

Create Gradient Layer

The CAGradientLayer class draws a color gradient over its background color.
 Here code for create a gradient layer.
I am using white and red color for gradient colors.

//Create Gradient
    UIColor *firstColor = [UIColor whiteColor];
    UIColor *secColor = [UIColor redColor];
    CAGradientLayer *layer = [CAGradientLayer layer];
    layer.frame = self.view.bounds;
    firstColor = [UIColor whiteColor];
    NSNumber *f1 = [NSNumber numberWithFloat:0.0];
    NSNumber *f2 = [NSNumber numberWithFloat:1.0];
    layer.locations = [NSArray arrayWithObjects:f1,f2,f3,f4, nil];
    layer.colors = @[(id)firstColor.CGColor,(id)secColor.CGColor];




//Add Gradient to View
    [self.view.layer insertSublayer:layer atIndex:0];
//Add Shadow on Gradient
    layer.cornerRadius = 1.0f;
    layer.masksToBounds = NO;
    layer.shadowColor = [UIColor blackColor].CGColor;
    layer.shadowOpacity = 0.2;
    layer.shadowRadius = 2;
    layer.shadowOffset = CGSizeMake(0.0f, 1.0f);
    layer.shadowPath = [UIBezierPath bezierPathWithRect:layer.bounds].CGPath;

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

Friday, 5 June 2015

Create an Ad Hoc IPA file for Testing.


All iOS apps and most Mac apps must be code signed and provisioned to launch on a device. Provisioning is the process of preparing and configuring an app to launch on devices and use app services.


It takes just a few steps to launch your app on a device:

1) First you need to enroll for the iOS Developer Program
   To do so, open a browser and go to iOS Dev Center, Sign in with Apple developer account and click on Learn More in the iOS Developer program section on the top right.


On the next page, click the Enroll Now button and follow the steps to complete the enrollment.

Note: It can take several days for your application to be accepted. Apple manually approves each application, which means that you won't have access to the iOS Developer Program until you get the green light from Apple.


2) Create Certificate Signing Request
After enrolling for the iOS Developer Program, you can see Certificates, Identifier & Profiles, iTunes Connect, Apple Developer Forums, and  Developer Support Center.





Click on the  Certificates, Identifier & Profiles section on the right


The provisioning process starts with the creation of an iOS Development Certificate. A certificate is an electronic document that links your digital identity with other information, such as your name, email, and company information.
A development certificate consists of a secret private key and a shared public key
Xcode uses the private key of the certificate to cryptographically sign your application binary. To obtain a development certificate, we first need to create a certificate signing request or CSR.
You can create a CSR using OS X's Keychain Access utility, Open the Keychain Access menu, select Certificate Assistant and choose the option labeled Request a Certificate From a Certificate Authority.

Fill out the Form by entering your email address and name with which you sign up for your Apple Developer account. Leave CA Email field, make sure to select the option  Saved to disk to save the certificate signing request to your system. 




Click on Continue, specify a location to save CSR and click Save.
In Keychain Access, under the Keys category, you can see that the private and public keys have been added to your login keychain. 

3) Create Developer Certificate
Go back to Apple Dev Center, and click Certificates, Identifiers & Profiles

Now select Certificate.

From the Top right click on " +"  button
after that you can see a new page





Select Certificate type and click on Continue
The next view tells you how to create a CSR. Feel free to click Continue since we already have a CSR ready to upload.

Upload CSR file and Click on Generate.
Click the Download button to download the certificate to your development machine.

Locate the certificate on your development certificate and double-click it to add it to your login keychain.

Repeat step 2 and 3 for  Distribution Certificate.

4) Add  Device

You cannot run an iOS application on a random device. You need to specify on which devices your iOS application should run by adding one or more iOS devices to the iOS Dev Center.

Browse to the Certificates, Identifiers & Profiles section of the iOS Dev Center, click the Devices tab in the iOS Apps section, and click the plus button in the top right. To register a device, enter a name for the device and he device's UDID. The UDID is an identifier that uniquely identifies an iOS device. Note that the UDID is not the same as the device's serial number.




5)Create An Apple ID
  An app ID is an identifier that uniquely identifies an application on iOS.
The app ID of an application consists of your application's bundle identifier prefixed with a unique 10 character bundle seed ID generated by Apple.

By default, the bundle identifier is your application's name prefixed with your project's company identifier. You can change the bundle identifier to whatever you like.

To create a new app ID in the iOS Dev Center, navigate to the Certificates, Identifiers & Profiles section, click iOS Apps, and choose App IDs from the menu on the left. To create a new app ID, click the plus button in the top right.
Give your App ID Description and Bundle ID .
Make sure you enter it in the section labeled Explicit App ID.

Click on Continue Button.

6) Create a Provisioning Profile
"A provisioning profile is a collection of assets that uniquely ties developers and devices to an authorized iOS Development Team and enables a device to be used for testing." In other words, a provisioning profile contains the information that the operating system needs to verify whether an application is permitted to run on a specific device. This implies that the provisioning profile needs to be installed on each device the application needs to run on."

In the Certificates, Identifiers & Profiles section of the iOS Dev Center, select the Provisioning Profiles tab in the iOS Apps section. Click the plus button in the top right to create a new provisioning profile. Select iOS App Development in the section labeled Development and click Continue.





In the next step, select the app ID you created









Select the development certificate from the list of certificates to associate the new provisioning profile with the correct certificate and click Continue.
Than, select the devices you wish to link to the provisioning profile. Remember that only these devices will be able to run your application during development.

 Give the provisioning profile a descriptive name, Click on Generate,
Download provision profile and double tap to install that.

Repeat Step 6 for creating new provisioning profile for "Ad Hoc" and "App Store".

7) Configuring the Project
Open the Xcode project and select the project from the Project Navigator on the left. Select the first item in the list of targets and click the tab labeled Build Settings at the top.



Search for the section titled Code Signing
Browse  provisioning profile
for Debug select Development provisioning profile
and for Release select Ad Hoc provisioning profile
  
In Code Signing Identity 
select Developer Certificate for Debug and Distribution Certificate for Release.


8) Create IPA File
Select XCode , from Menu  select clean under "Product"  Option.
after successful cleanup select Archive under "Product"  Option.



after success, you can see another window

Click on Export, select or add developer account and specify location for save file.
you can find IPA  file on specify location.