Saturday, 15 November 2014

Find the Fonts in your App and added into Array

Find the font and Stored into array. The array is used in Tableview to show the Font List. 


ViewController.h File

NSMutableArray *font_names;


ViewController.m File

-(void)fontfamily
{
    font_names = [[NSMutableArray alloc]init];
    
    for (NSString* family in [UIFont familyNames])
    {
        NSLog(@"%@", family);
        
        for (NSString* name in [UIFont fontNamesForFamilyName:family])
        {
            NSLog(@"  %@", name);
            [font_names addObject:name];
        }
    }
}


Import the Google Analytics Library in your App

AppDelegate.h File

#import <UIKit/UIKit.h>
#import "GAI.h"

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{

}
@property (strong, nonatomic) UIWindow *window;
@property(nonatomic, strong) id<GAITracker> tracker;

@end

AppDelegate.m File

#import "AppDelegate.h"

//Set your tracking ID here
static NSString *const kTrackingId = @"UA-XXXXXXXX-X”;

static NSString *const kAllowTracking = @"allowTracking";

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    NSDictionary *appDefaults = @{kAllowTracking: @(YES)};
    [[NSUserDefaults standardUserDefaults] registerDefaults:appDefaults];


    // User must be able to opt out of tracking
    [GAI sharedInstance].optOut =
    ![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];


    // Initialise Google Analytics with a 120-second dispatch interval. There is a
    // tradeoff between battery usage and timely dispatch.
    [GAI sharedInstance].dispatchInterval = 120;
    [GAI sharedInstance].trackUncaughtExceptions = YES;
    self.tracker = [[GAI sharedInstance] trackerWithName:@"AppName"
                                              trackingId:kTrackingId];

    return YES;
}


- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [GAI sharedInstance].optOut = ![[NSUserDefaults standardUserDefaults] boolForKey:kAllowTracking];
}


ViewController.h File

#import <UIKit/UIKit.h>
#import "AppDelegate.h"
@interface ViewController : GAITrackedViewController
{
    AppDelegate *appDelegate;
}
@end


ViewController.m File

#import "ViewController.h"

#import "GAI.h"
#import "GAIDictionaryBuilder.h"

@interface ViewController ()

@end

@implementation ViewController


//Track the Pages
- (void)viewDidLoad
{
    appDelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    self.screenName = @“Home Screen";
}

/**** or ****/

-(void)viewWillAppear:(BOOL)animated
{
    appDelegate=(AppDelegate*)[[UIApplication sharedApplication]delegate];
    self.screenName = @“Home Screen";
}


//Track the Button Click Event
- (IBAction)loginButtonClicked:(id)sender
{
NSMutableDictionary *event =
                [[GAIDictionaryBuilder createEventWithCategory:@"Login Submit"
                                                        action:@"Success"
                                                         label:nil
                                                         value:nil] build];
                [[GAI sharedInstance].defaultTracker send:event];
                [[GAI sharedInstance] dispatch];

}

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 renderInContext: UIGraphicsGetCurrentContext()];
        image = UIGraphicsGetImageFromCurrentImageContext();
        
        self.Scrollview.contentOffset = savedContentOffset;
        self.Scrollview.frame = savedFrame;
    }
    UIGraphicsEndImageContext();

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

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    UIAlertView *alert;
    if (error)
    {
        alert = [[UIAlertView alloc] initWithTitle:@"Error"
                                           message:@"Unable to save image to Photo Album."
                                          delegate:self cancelButtonTitle:@"Ok"
                                 otherButtonTitles:nil];
    }
    else
    {
        alert = [[UIAlertView alloc] initWithTitle:@"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.width,  self.Scrollview.contentSize.height);

    // sets the size and position of the image and text
    CGRect imageBounds = CGRectMake(100, 100, self.Scrollview.contentSize.width,  self.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
    }
}