Monday 22 September 2014

Snapshot a Scroll View & Save into Photo Library

.m File
-(void)Generate_Image
{
UIGraphicsBeginImageContext(self.Scrollview.contentSize);
    {
        CGPoint savedContentOffset = self.Scrollview.contentOffset;
        CGRect savedFrame = self.Scrollview.frame;
        self.Scrollview.contentOffset = CGPointZero;
        
        [self.Scrollview.layer renderInContextUIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        self.Scrollview.contentOffset = savedContentOffset;
        self.Scrollview.frame = savedFrame;
    }
    UIGraphicsEndImageContext();

    //Save Image to Local Library
  UIImageWriteToSavedPhotosAlbum(imageself@selector(image:didFinishSavingWithError:contextInfo:), nil);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    UIAlertView *alert;
    if (error)
    {
        alert = [[UIAlertView allocinitWithTitle:@"Error"
                                           message:@"Unable to save image to Photo Album."
                                          delegate:self cancelButtonTitle:@"Ok"
                                 otherButtonTitles:nil];
    }
    else
    {
        alert = [[UIAlertView allocinitWithTitle:@"Success"
                                           message:@"Image saved to Photo Album."
                                          delegate:self cancelButtonTitle:@"Ok"
                                 otherButtonTitles:nil];
    }
    [alert show];
}

Generate PDF file for Export the Image’s & Data’s

.h File
@interface ViewController : UIViewController<UIDocumentInteractionControllerDelegate>
{
UIAlertView *Alert;
}
@end

.m File
-(IBAction)Send_Mail:(id)sender
{
[self generate_PDF];

   if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
        mailComposer.mailComposeDelegate = self;
        [mailComposer setSubject:@"Results"];
        
        NSString* fileName = @"Result.pdf";
        
        NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
        NSString *path = [arrayPaths objectAtIndex:0];
        NSString* pdfFileName = [path stringByAppendingPathComponent:fileName];
        NSData *myData = [NSData dataWithContentsOfFile:pdfFileName];
        
        [mailComposer addAttachmentData:myData mimeType:@"application/pdf" fileName:fileName];
        
        [self presentViewController:mailComposer animated:YES completion:nil];
    }
    
    else
    {
        UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"No Mail Accounts" message:@"Please set up a Mail account in order to send email." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
    }
}

-(IBAction)Save_Pdf:(id)sender
{
[self generate_PDF];
    [self open_pdf];
}

- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Cancelled" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Sent" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Sending Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;
        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}

-(void)generate_PDF
{
    NSString *docDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *pdfPath = [docDirectory stringByAppendingPathComponent:@"Result.pdf"];

    // set the size of the page (the page is in landscape format)
    CGRect pageBounds = CGRectMake(0, 0, self.Scrollview.contentSize.widthself.Scrollview.contentSize.height);

    // sets the size and position of the image and text
    CGRect imageBounds = CGRectMake(100, 100, self.Scrollview.contentSize.widthself.Scrollview.contentSize.height);
    CGRect textBounds = CGRectMake(0.0f, 0.0f, 182.0f, 375.0f);
    
    
    UIImage *image_val = [UIImage imageNamed:@"results_page.png"];
    UILabel *textLabel = [[UILabel alloc]init];

    //set the image (or) snapshot image (or) any other image
    UIImage *theImage = image_val;

    // set the text (or) data from Array
    textLabel.text = @"Test the values";

    // create and save the pdf file
    UIGraphicsBeginPDFContextToFile(pdfPath, pageBounds, nil);
    {
        UIGraphicsBeginPDFPage();
        [textLabel drawTextInRect:textBounds];
        [theImage drawInRect:imageBounds];
        
    }
    UIGraphicsEndPDFContext();
}


-(void)open_pdf
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"Result.pdf"];
    
    NSURL *url = [NSURL fileURLWithPath:filePath];
    UIDocumentInteractionController *docController = [UIDocumentInteractionController alloc];
    docController = [UIDocumentInteractionController interactionControllerWithURL:url];
    docController.delegate = self;
    BOOL isValid = [docController presentOpenInMenuFromRect:self.Btn.frame inView:self.view animated:YES];
    
    if(isValid)
    {
        docController.delegate = self;
    }
    else
    {
        UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"Sorry" message:@"You need iBooks to view this file" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Install", nil];
        [alert show];
    }
}

#pragma mark - UIAlertview Delegate Method
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 1)
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/in/app/ibooks/id364709193?mt=8"]]];
}


#pragma mark - UIDocumentInteractionController Delegate
- (void)documentInteractionController:(UIDocumentInteractionController *)controller didEndSendingToApplication:(NSString *)application
{
    docController = nil;
}

- (void)documentInteractionControllerDidDismissOpenInMenu:(UIDocumentInteractionController *)controller
{
    docController = nil;

}

Generate CSV file for Export the datas’s

.h File
UIAlertView *Alert;
BOOL mail_status;

.m File:
-(void)Generate_CSV
{
    NSString *csv_values = [NSString stringWithFormat:@“Names”];   

NSString *string_heading =@"Others”;
    csv_values = [NSString stringWithFormat:@"%@, ""%@""", csv_values,string_heading];
    
    for (int i=0; i<[Array count]; i++)
    {
        NSString *str_products = [Array objectAtIndex:i];
        str_products = [str_products stringByReplacingOccurrencesOfString:@" " withString:@""];
        csv_values = [NSString stringWithFormat:@"%@, ""\n""""%@""", csv_values,str_products];
    }
    
    if (mail_status)
    {
        NSData *csv_data = [csv_values dataUsingEncoding:NSUTF8StringEncoding];
        
        if ( [MFMailComposeViewController canSendMail] )
        {
            MFMailComposeViewController *mailComposer = [[MFMailComposeViewController alloc] init];
            mailComposer.mailComposeDelegate = self;
            [mailComposer addAttachmentData:csv_data mimeType:@"text/csv" fileName:@"results.csv"];
            [mailComposer setSubject:@"Results CSV File”];
            
            [self presentViewController:mailComposer animated:YES completion:NULL];
        }
        else
        {
              UIAlertView* alert=[[UIAlertView alloc]initWithTitle:@"No Mail Accounts" message:@"Please set up a Mail account in order to send email." delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
               [alert show];
        }
    }
    
    else
    {
        NSString *file = @"/results.csv";
        NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *docDirectory = [arrayPaths objectAtIndex:0];
        NSString *filePaths = [docDirectory stringByAppendingString:file];
        [csv_values writeToFile:filePaths atomically:YES encoding:NSUTF8StringEncoding error:nil];
        
        [self open_csv];
    }

}


- (void) mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Cancelled" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;

        case MFMailComposeResultSaved:
            NSLog(@"Mail saved");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Saved" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;

        case MFMailComposeResultSent:
            NSLog(@"Mail sent");
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Sent" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;

        case MFMailComposeResultFailed:
            NSLog(@"Mail sent failure: %@", [error localizedDescription]);
            Alert = [[UIAlertView alloc]initWithTitle:@"Message" message:@"E-Mail Sending Failed" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [Alert show];
            break;

        default:
            break;
    }
    
    // Close the Mail Interface
    [self dismissViewControllerAnimated:YES completion:NULL];
}


-(void)open_csv
{
    csv_view.hidden = NO;
    csv_view.layer.masksToBounds = YES;
    
    //Show the Excel in WebView
    NSString *file = @"/results.csv";
    NSArray *arrayPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirectory = [arrayPaths objectAtIndex:0];
    NSString *filePath = [docDirectory stringByAppendingString:file];
    if (filePath)
    {
        NSURL *url=[NSURL fileURLWithPath:filePath];
        NSURLRequest *req=[NSURLRequest requestWithURL:url];
        [csv_content loadRequest:req]; //csv_content -- WebView
    }
}


-(IBAction)csv_close:(id)sender
{
    csv_view.hidden = YES;
}

Grouping the Array values using Keys

.m file
NSArray *array = @[@{@"groupId" : @"1", @"name" : @"matt"},
                       @{@"groupId" : @"2", @"name" : @"john"},
                       @{@"groupId" : @"3", @"name" : @"steve"},
                       @{@"groupId" : @"4", @"name" : @"alice"},
                       @{@"groupId" : @"1", @"name" : @"bill"},
                       @{@"groupId" : @"2", @"name" : @"bob"},
                       @{@"groupId" : @"3", @"name" : @"jack"},
                       @{@"groupId" : @"4", @"name" : @"dan"},
                       @{@"groupId" : @"1", @"name" : @"kevin"},
                       @{@"groupId" : @"2", @"name" : @"mike"},
                       @{@"groupId" : @"3", @"name" : @"daniel"},
                       ];
    
    NSMutableArray *resultArray = [NSMutableArray new];
    NSArray *groups = [array valueForKeyPath:@"@distinctUnionOfObjects.groupId"];

    for (NSString *groupId in groups)
    {

        NSMutableDictionary *entry = [NSMutableDictionary new];
        [entry setObject:groupId forKey:@"groupId"];
        
        NSArray *groupNames = [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"groupId = %@", groupId]];
        
        for (int i = 0; i < groupNames.count; i++)
        {
            NSString *name = [[groupNames objectAtIndex:i] objectForKey:@"name"];
            [entry setObject:name forKey:[NSString stringWithFormat:@"name%d", i + 1]];
        }

        [resultArray addObject:entry];

    }

Scroll Two UITableView Simultaneously (UITableView Scrolling Synchronisation)

.m File
- (void)scrollViewDidScroll:(UIScrollView *)scrollView 
{
    if (scrollView == self.firstTable) 
{
        self.secondTable.contentOffset = scrollView.contentOffset;
    } 
else if (scrollView == self.secondTable) 
{
        self.firstTable.contentOffset = scrollView.contentOffset
    }
}