Saturday 15 November 2014

In Horizontal Scrollview to Find a page using Page Controller

In ScrollView Settings, Tick the PagingEnabled Button.


ViewController.m File

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    int page = scroll.contentOffset.x / scroll.frame.size.width;
    page_controll.currentPage = page;
}

Lock a Orientation for App in XCode 6.1

In Project Settings should change into support orientation to Unlock(Tick-Mark) the all items.

The code used to one Time Orientation Lock. 
When run the (Portrait-Lock)code in your app, The app is support Autorotate Function. If you want to Autorotate, You can run the (Portrait-UnLock)code in your app. 

If want use in Single Page, Use the (Portrait-Lock)code in viewWillAppear (or) viewDidAppear and (Portrait-UnLock)code used in viewWillDisappear (or) Navigate Button (or) Back Button. 


AppDelegate.h File

@property (nonatomic) BOOL screenIsPortraitOnly;


AppDelegate.m File

- (NSUInteger)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    NSUInteger orientations = UIInterfaceOrientationMaskPortrait;
    if (self.screenIsPortraitOnly)
    {
        return UIInterfaceOrientationMaskPortrait;
    }
    else
    {
        if(self.window.rootViewController)
        {
            UIViewController *presentedViewController = [[(UINavigationController *)self.window.rootViewController viewControllers] lastObject];
            orientations = [presentedViewController supportedInterfaceOrientations];
        }
        return orientations;
    }
}



ViewController.m File

//Orientation UnLock Code
-(void)viewWillAppear:(BOOL)animated
{
    [self portraitUnLock];
}

/**** or ****/

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:true];
    [self portraitUnLock];
}

//Orientation Lock Code
-(void)viewWillDisappear:(BOOL)animated
{
    [self portraitLock];
}

/**** or ****/

//Button Code
- (IBAction)Back_Clicked:(id)sender
{
    [self portraitLock];
[self.navigationController popViewControllerAnimated:YES];
}


-(void)portraitLock
{
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = true;
}

-(void)portraitUnLock
{
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    appDelegate.screenIsPortraitOnly = false;

}

VideoPlayer Open when App is Launched

Add the Framework File into Project : MediaPlayer.framework 

AppDelegate.h File

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

@class MPMoviePlayerController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    MPMoviePlayerController *moviePlayer;
    
    UIView *view_background;
}

@property (strong, nonatomic) UIWindow *window;

@end

AppDelegate.m File

#import "AppDelegate.h"
#import "ViewController.h"

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    ViewController *ViewControl = [[ViewController alloc] initWithNibName:@"ViewController" bundle:nil];
    UINavigationController *detailNavigationController = [[UINavigationController alloc] initWithRootViewController: ViewControl];
    self.window.rootViewController = detailNavigationController;
    [self.window makeKeyAndVisible];


view_background = [[UIView alloc]init];
    
    moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@“video_Name” ofType:@"mp4"]]];
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
    {
        view_background.frame = CGRectMake(0, 0, 1024, 768);
        moviePlayer.view.frame = CGRectMake(112, 170, 800, 427);
    }
    else
    {
        NSString *version = [[UIDevice currentDevice]systemVersion];
        float ver = [version floatValue];
        
        if (ver >= 8.0)
        {
            moviePlayer.view.frame = CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
        }
        else
        {
            moviePlayer.view.frame = CGRectMake(0, 0, self.window.frame.size.height, self.window.frame.size.width);
        }
        
        view_background.frame = moviePlayer.view.frame;
    }
    view_background.backgroundColor = [UIColor whiteColor];
    moviePlayer.backgroundView.backgroundColor = [UIColor whiteColor];
    [moviePlayer setControlStyle:MPMovieControlStyleNone];
    [moviePlayer setFullscreen:YES animated:YES];
    moviePlayer.shouldAutoplay = YES;
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(moviePlayBackDidFinish:)
                                                 name:MPMoviePlayerPlaybackDidFinishNotification
                                               object:moviePlayer];
    [moviePlayer play];
    [view_background addSubview:moviePlayer.view];
    [detailNavigationController.view addSubview:view_background];
    
    return YES;
}


-(void) moviePlayBackDidFinish:(NSNotification*)notification
{
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDuration:1.0];
    [UIView animateWithDuration:0.5
                          delay:0.1
                        options: UIViewAnimationOptionCurveEaseOut
                     animations:^
     {
         if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
         {
             view_background.frame = CGRectMake(-1024, 0, 1024, 768);
         }
         else
         {
             view_background.frame = CGRectMake(-568, 0, 568, 320);
         }
     }
                     completion:^(BOOL finished)
     {
         NSLog(@"Completed");
         [moviePlayer.view removeFromSuperview];
         [view_background removeFromSuperview];
     }];
    [UIView commitAnimations];
}


Download Images from URL & Update the Image Count (DB-SQLite)

AppDelegate.h File

#import <UIKit/UIKit.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    NSString *databasePath;
}

@property (strong, nonatomic) UIWindow *window;

- (NSString *) getDatabasepath;

@end


AppDelegate.m File

#import "AppDelegate.h"

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [self checkAndCreateDatabase];
}


//DB is copied from Project to Document Directory
-(void) checkAndCreateDatabase
{
BOOL success;
    
NSError *error;
    
NSFileManager *fileManager = [NSFileManager defaultManager];
    
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
NSString *documentsDirectory=[paths objectAtIndex:0];
    
databasePath=[documentsDirectory stringByAppendingFormat:@“/DB.sqlite"];
    
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"DB.sqlite"];
    
success = [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:&error];
}


//Find the DB Path from Document Directory
- (NSString *) getDatabasepath
{
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory=[paths objectAtIndex:0];
databasePath=[documentsDirectory stringByAppendingFormat:@"/DB.sqlite"];
return databasePath;
}


DBHelpher.h File

@interface DBHelper : NSObject
{
    NSMutableArray* tempArray;
    NSMutableDictionary* tempDict;
}

-(NSMutableArray *)get_images_from_web;
-(void)updateDate:(NSString *)dte

@end


DBHelpher.m File

#import "DBHelper.h"
#import "AppDelegate.h"

@implementation DBHelper

static sqlite3_stmt *Images_statement = nil;
static sqlite3_stmt *Images_count_statement = nil;

-(NSMutableArray *)get_images_from_web
{
    tempArray = [[NSMutableArray alloc] init];
    NSString *status=@"Y";
    NSString *databasePath=[(AppDelegate *)[[UIApplication sharedApplication] delegate] getDatabasepath];
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        const char *sql = "select Logo_url from tablename where status = 'Y'";
        if (sqlite3_prepare_v2(database, sql, -1, &Images_statement, NULL) != SQLITE_OK)
        {
            NSAssert1(0, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database));
        }
        sqlite3_bind_text(Images_statement, 1, [status UTF8String],-1,SQLITE_TRANSIENT);
        
        // Loop through the results and add them to the feeds array
        while(sqlite3_step(Images_statement) == SQLITE_ROW)
        {
            NSString *imageurl = [NSString stringWithFormat:@"%s",sqlite3_column_text(Images_statement, 0)];
            [tempArray addObject:imageurl];
        }
        sqlite3_reset(Images_statement);
        sqlite3_finalize(Images_statement);
    }
    sqlite3_close(database);
    return tempArray;
}


-(void)update_img_count:(int)count_val
{
    NSString *sql = @"";
    NSString *databasePath=[(AppDelegate *)[[UIApplication sharedApplication] delegate] getDatabasepath];
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        sql = [NSString stringWithFormat:@"UPDATE images_count_table SET img_count = '%d' WHERE serial = 1", count_val];
        if(sqlite3_prepare_v2(database, [sql UTF8String], -1, & Images_count_statement, NULL) != SQLITE_OK)
        {
            NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
        }
        NSLog(@"update query : %@", sql);
        
        if(SQLITE_DONE != sqlite3_step(Images_count_statement))
            NSLog(@"Error while inserting data. '%s'", sqlite3_errmsg(database));

        sqlite3_reset(Images_count_statement);
        sqlite3_finalize(Images_count_statement);
    }
    sqlite3_close(database);
}


ViewController.h File

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


@interface ViewController : GAITrackedViewController
{
    DBHelper *dbHelper;
}
@end


ViewController.m File

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController


-(void)viewWillAppear:(BOOL)animated
{
dbHelper = [[DBHelper alloc] init];
    [self Images_Add_to_Local];
[dbHelper update_img_count:20];
}


-(void)Images_Add_to_Local
{
    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    if (![[defaults objectForKey:@"Images_From_Web"] isEqualToString:@"Downloaded"])
    {
        [defaults setObject:@"Downloaded" forKey:@"Images_From_Web"];
        [defaults synchronize];
        
        NSMutableArray *imagesArray = [dbHelper get_images_from_web];
        
        for (int i=1; i<=[imagesArray count]; i++)
        {
            NSString *str_image_name = [NSString stringWithFormat:@"%d.jpg",i];
            NSURL *url = [NSURL URLWithString:[imagesArray objectAtIndex:i-1]];
            NSData *pictureData = [NSData dataWithContentsOfURL:url];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documents = [paths objectAtIndex:0];
            NSString *finalPath = [documents stringByAppendingPathComponent:str_image_name];
            [pictureData writeToFile:finalPath atomically:YES];
        }
    }

}

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

}