Monday, 23 December 2013

Mail with attachments in iOS?

HI,

Here am using MFMailCompose to create mail and attach a screen shot with it.

Its very easy ,and also for this we have to import "#import <MessageUI/MessageUI.h>".

In  ViewController.h File

#import <UIKit/UIKit.h>
#import <MessageUI/MessageUI.h>
@interface ViewController : UIViewController <MFMailComposeViewControllerDelegate>
@property (strong, nonatomic) IBOutlet UIWebView *webview;

- (IBAction)openMail:(id)sender;
@end




In ViewController.m file


#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
{
    NSArray *paths;
    NSString *filename,*newPath;
}
@end

@implementation ViewController

- (void)viewDidLoad
{

    // Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)takescreenshotes{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);
    filename=@"latest.png"; //create a custome file name for your screen shots
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    newPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename];
   
    [data writeToFile:newPath atomically:YES]; //Path to store the screen shots
    UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:data], nil, nil, nil);
}














- (IBAction)openMail:(id)sender
{
    [self takescreenshotes];
    if ([MFMailComposeViewController canSendMail])
    {
        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];
       
        mailer.mailComposeDelegate = self;
       
        [mailer setSubject:@"Email Subject"];
       
        NSArray *toRecipients = [NSArray arrayWithObjects:@"fisrtMail@example.com", nil];
        [mailer setToRecipients:toRecipients];
       
        UIImage *myImage = [UIImage imageWithContentsOfFile:newPath];
        NSData *imageData = UIImagePNGRepresentation(myImage);
        [mailer addAttachmentData:imageData mimeType:@"image/png" fileName:@"mobiletutsImage"];
       
        NSString *emailBody = @"Please check the attached image: Naveen";
        [mailer setMessageBody:emailBody isHTML:NO];
       
        // only for iPad
        // mailer.modalPresentationStyle = UIModalPresentationPageSheet;
       
        [self presentModalViewController:mailer animated:YES];
       
        //[mailer release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles: nil];
        [alert show];

    }
   
}



#pragma mark - MFMailComposeController delegate


- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error


{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            NSLog(@"Mail cancelled: you cancelled the operation and no email message was queued");
            break;
        case MFMailComposeResultSaved:
            NSLog(@"Mail saved: you saved the email message in the Drafts folder");
            break;
        case MFMailComposeResultSent:
            NSLog(@"Mail send: the email message is queued in the outbox. It is ready to send the next time the user connects to email");
            break;
        case MFMailComposeResultFailed:
            NSLog(@"Mail failed: the email message was nog saved or queued, possibly due to an error");
            break;
        default:
            NSLog(@"Mail not sent");
            break;
    }
   
    [self dismissModalViewControllerAnimated:YES];
}




@end



and the run time window looks like






You can download the code from here


























How to take screen shots programmatically ??

Hi.
In this tutorial ,am talking about how we can take screen shots programmatically  instead of "Home+Power" button combination on your device.

It's very simple and i have only two files "ViewController.h" and "ViewController.m"
and you have to import "#import <QuartzCore/QuartzCore.h>".

here we go ..

in my ViewController.h file

i have one method for UIButton.



#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
- (IBAction)openMail:(id)sender;
@end




In my ViewController.m file


#import "ViewController.h"
#import <QuartzCore/QuartzCore.h>
@interface ViewController ()
{
    NSArray *paths;
    NSString *filename,*newPath;
}
@end

@implementation ViewController

- (void)viewDidLoad
{
        [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)takescreenshotes{
    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0);

    [self.view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    NSData * data = UIImagePNGRepresentation(image);

    filename=@"latest.png"; //create a custome file name for your screen shots
 
    paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    newPath = [[paths objectAtIndex:0] stringByAppendingPathComponent:filename];
   
    [data writeToFile:newPath atomically:YES]; //Path to store the screen shots
 
    UIImageWriteToSavedPhotosAlbum([UIImage imageWithData:data], nil, nil, nil);
}

- (IBAction)openMail:(id)sender
{
    [self takescreenshotes];

 }

 
@end


and my xib looks like








You can download the code from here













Monday, 9 December 2013

QR Code Reader

The ZBar Barcode Reader iPhone® App is a simple demonstration of the ZBar library on the iPhone 3GS and iPhone 4 platforms. Using the app you can:
  • Scan EAN/UPC codes and link to web sites that perform product searches. Links to Google, Amazon and the Internet UPC Database are predefined.
  • Scan QR codes containing URLs and link directly to the web site.
  • Scan QR codes containing an E-mail address and send mail.
  • Scan a UPS or FedEx tracking number and link to the package tracking web page.
  • Maintain a simple list of scanned barcodes.
  • Send an E-mail containing a single barcode or your entire list of scanned barcodes.
  • Cut and paste barcode data into other apps.
Please note that this app is just about the barcodes; specifically it is not a full featured "shopping app". We do not scrape the web for product or pricing information, perform localized searches or implement any of the other fancy features that you would expect to find in such an application.

Wednesday, 27 November 2013


Inspiring Steve Job quotes that will make you want to change "The World"



 



Let’s go invent tomorrow instead of worrying about what happened yesterday.



 



 



 



Creativity is just connecting things. When you ask creative people how they did something, they feel a little guilty because they didn’t really do it, they just saw something. It seemed obvious to them after a while. 



 



 



 



If you really look closely, most overnight successes took a long time. 



 



 



But innovation comes from people meeting up in the hallways or calling each other at 10:30 at night with a new idea, or because they realized something that shoots holes in how we’ve been thinking about a problem. 



 



 



We’re here to put a dent in the universe. Otherwise why else even be here? 



 



 Deciding what not to do is as important as deciding what to do.



 



 



I’m convinced that about half of what separates the successful entrepreneurs from the non-successful ones is pure perseverance.



 



 



Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma — which is living with the results of other people’s thinking. Don’t let the noise of others’ opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary. 



 



 Sometimes life is going to hit you in the head with a brick. Don’t lose faith.



 



The heaviness of being successful was replaced by the lightness of being a beginner again — less sure about everything. It freed me to enter one of the most creative periods of my life.



 



 You’ve baked a really lovely cake, but then you’ve used dog shit for frosting.



 



 



If you don’t love something, you’re not going to go the extra mile, work the extra weekend, challenge the status quo as much.



 



 



Details matter, it’s worth waiting to get it right. 



 



 



That’s been one of my mantras — focus and simplicity. Simple can be harder than complex. You have to work hard to get your thinking clean to make it simple. But it’s worth it in the end because once you get there, you can move mountains. 



 



 



 



No one wants to die. Even people who want to go to heaven don’t want to die to get there. And yet death is the destination we all share. No one has ever escaped it. And that is as it should be, because Death is very likely the single best invention of Life. It is Life’s change agent. It clears out the old to make way for the new. Right now the new is you, but someday not too long from now, you will gradually become the old and be cleared away. Sorry to be so dramatic, but it is quite true. 



 



 

Monday, 25 November 2013






Block??

Blocks are “anonymous functions” and can be defined inline.
Blocks capture read-only copies (unless defined with __block, more on that later) of local variables, similar to “closures” in other languages.

Block variable

• To define a block variable, the ^ operator is used.
• BOOL ( ^isInputEven)(int) = ^(int input) {
if(input % 2 == 0) return YES;
else
return NO;

check image**


• Call to a block is similar to c function call int x = -101;
NSLog(@"%d %@ number", x, isInputEven(x) ? @"is an even" : @"is not an even");
Output is:
-101 is not an even number

Blocks and variable scope

float price = 1.99;
float (^finalPrice)(int) = ^(int quantity) {
// Notice local variable price is accessible in the block
return quantity * price; };
• thecodeinthebodyreferencesthevariable ‘price’ which is defined outside the block.


• The output for the log statement is: Ordering 10 units, final price is: $19.90
• Now change the price and run the program price = .99;
NSLog(@"Ordering %d units, final price is: $%2.2f", orderQuantity, finalPrice(orderQuantity));

• The output for the block, with the price variable updated is:
Ordering 10 units, final price is: $19.90

Using ___block Storage Modifier

• To allow a variable defined outside a block to be mutable, apply the ___block storage type modifier:
___block float price = 1.99;
float (^finalPrice)(int) = ^(int quantity) {
return quantity * price; };
int orderQuantity = 10; price = .99;

• The output for the block, with the price variable updated is:
• With block storage modifier – Ordering 10 units, final price is: $9.90


Passing block as parameter

• Since blocks are “variables” you can pass blocks to methods and functions.
• -(NSArray*)each:(void(^)(id))block;
• - (NSArray *)each:(void (^)(id object))block {
for(id mObject in self) block(mObject); return self;
}




int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSArray *array = [NSArray arrayWithObjects:@"Number one", @"Number two", nil];
[array each:^(id object) { NSLog(object);
}];

More details :Apple Docs

Sunday, 24 November 2013

Hi..

If you need any particular topic tutorial please mention those topics as a comment to this post.
So i can add that one also.

And the next tutorial's am going to submit is


"Earn money from your ios App's" 


Hopefully i will post it today night itself...


There are mainly 2 types
1. Using iOS In App Purchase
2.Using Google AdMobs

Monday, 2 September 2013

Game Kit Authentication


  • Documentation

Read Me About GKAuthentication
=================================================================
GKAuthentication is a sample application that shows how to correctly 
perform GameKit Authentication. This code is completely copy and paste-able.


IMPORTANT: When adding support for Game Center to an application, it is not
enough to simply add the necessary code to your application.  You also
need to configure your app in iTunes Connect to match your desired
configuration.  

=================================================================
BUILD REQUIREMENTS:

This project was built with Xcode 3.2.4 and iOS SDK 4.2

=================================================================
RUNTIME REQUIREMENTS:

The project requires iOS 4.2 and a GameCenter account to run.

=================================================================
PACKAGING LIST:
- ReadMe.txt -- This file.
- GKAuthentication.xcodeproj --  Xcode project for this sample. 
- Resources -- The project nib, images, and so on.
- Classes/GKAuthenticationAppDelegate.h -- Declaration of the best 
    practices
- Classes/GKAuthenticationAppDelegate.m -- Contains the best practices of 
    adding authentication to a project. 
- main.m -- The main function of this sample.


=================================================================
Copyright (C) 2011 Apple Inc. All rights reserved.



  • Design






  • Code

GKAuthenticationAppDelegate.h

Copyright (C) 2011 Apple Inc. All Rights Reserved.

 */

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

// Preferred method for testing for Game Center 
BOOL isGameCenterAvailable();


@class MainViewController;

@interface GKAuthenticationAppDelegate : NSObject <UIApplicationDelegate> {
    UIWindow *window;
    UIViewController *mainViewController;
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UIViewController *mainViewController;

// currentPlayerID is the value of the playerID last time GameKit authenticated.
@property (retain,readwrite) NSString * currentPlayerID;

// isGameCenterAuthenticationComplete is set after authentication, and authenticateWithCompletionHandler's completionHandler block has been run. It is unset when the applicaiton is backgrounded. 
@property (readwrite, getter=isGameCenterAuthenticationComplete) BOOL gameCenterAuthenticationComplete;

@end


----------------------------------------------------------------

GKAuthenticationAppDelegate.m


#include <sys/types.h>
#include <sys/sysctl.h>

#import "GKAuthenticationAppDelegate.h"


@implementation GKAuthenticationAppDelegate


@synthesize window;
@synthesize mainViewController;


#pragma mark -
#pragma mark Game Center Support

@synthesize currentPlayerID, 
            gameCenterAuthenticationComplete;



#pragma mark -
#pragma mark Game Center Support

// Check for the availability of Game Center API. 
BOOL isGameCenterAPIAvailable()
{
    // Check for presence of GKLocalPlayer API.
    Class gcClass = (NSClassFromString(@"GKLocalPlayer"));
    
    // The device must be running running iOS 4.1 or later.
    NSString *reqSysVer = @"4.1";
    NSString *currSysVer = [[UIDevice currentDevice] systemVersion];
    BOOL osVersionSupported = ([currSysVer compare:reqSysVer options:NSNumericSearch] != NSOrderedAscending);
    
    return (gcClass && osVersionSupported); 
}

#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions  
{        
    // Override point for customization after application launch.  

    // Add the main view controller's view to the window and display.
    [self.window addSubview:mainViewController.view];
    [self.window makeKeyAndVisible];
    
    self.gameCenterAuthenticationComplete = NO;
    
    if (!isGameCenterAPIAvailable()) {
        // Game Center is not available. 
        self.gameCenterAuthenticationComplete = NO;
    } else {
        
        GKLocalPlayer *localPlayer = [GKLocalPlayer localPlayer];
        
        /*
         The authenticateWithCompletionHandler method is like all completion handler methods and runs a block
         of code after completing its task. The difference with this method is that it does not release the 
         completion handler after calling it. Whenever your application returns to the foreground after 
         running in the background, Game Kit re-authenticates the user and calls the retained completion 
         handler. This means the authenticateWithCompletionHandler: method only needs to be called once each 
         time your application is launched. This is the reason the sample authenticates in the application 
         delegate's application:didFinishLaunchingWithOptions: method instead of in the view controller's 
         viewDidLoad method.
         
         Remember this call returns immediately, before the user is authenticated. This is because it uses 
         Grand Central Dispatch to call the block asynchronously once authentication completes.
         */
        [[GKLocalPlayer localPlayer] authenticateWithCompletionHandler:^(NSError *error) {
            // If there is an error, do not assume local player is not authenticated. 
            if (localPlayer.isAuthenticated) {
                
                // Enable Game Center Functionality 
                self.gameCenterAuthenticationComplete = YES;

                if (! self.currentPlayerID || ! [self.currentPlayerID isEqualToString:localPlayer.playerID]) {

                    // Current playerID has changed. Create/Load a game state around the new user. 
                    self.currentPlayerID = localPlayer.playerID;
                    
                    // Load game instance for new current player, if none exists create a new.
                }
            } else {     
                // No user is logged into Game Center, run without Game Center support or user interface. 
                self.gameCenterAuthenticationComplete = NO;
            }
        }];
    }    
    
    // The user is not authenticated until the Completion Handler block is called. 
    return YES;
}

    

- (void)applicationDidEnterBackground:(UIApplication *)application  
{
    /*
     Invalidate Game Center GKAuthentication and save game state, so the game doesn't start until the GKAuthentication 
     Completion Handler is run. This prevents a new user from using the old users game state.
     */
    self.gameCenterAuthenticationComplete = NO;
}


/*
- (void)applicationWillEnterForeground:(UIApplication *)application  
{
    // Do not call authenticateWithCompletionHandler again here.Once you have set the CompletionHandler in the 
    // original call in application:didFinishLaunchingWithOptions, it will dispatch the block next time the 
    // application enters foreground. 
}
*/



#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application  
{
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc 
{
    [currentPlayerID release];
    [mainViewController release];
    [window release];
    [super dealloc];
}

@end

----------------------------------------------------------------