Wednesday, 4 April 2018

Gmail Implementation in iOS

Gmail Implementation in iOS



Step 1: Turn on the Gmail API


Click the button below to enable the API and download your credentials file. When prompted, ensure that you:
  • Select the platform iOS.
  • Enter com.example.QuickstartApp as the Bundle ID.
  • Download the client configuration file credentials.plist.


You Can Enable API :-    CLICK HERE

Step 2: Prepare the workspace


  1. Open Xcode and create a new project:
    1. Click File > New > Project, select the iOS > Application > Single View Application template, and clickNext.
    2. Set the Product Name to "QuickstartApp", Organization Identifier to "com.example", and Language toObjective-C. Click Next.
    3. Select a destination directory for the project and click Create.
  2. Close the project by clicking File > Close Project.
  3. Open a Terminal window and navigate to the directory that contains the QuickstartApp.xcodeproj file you just created.
  4. Run the following commands to create the Podfile, install the library, and open the resulting XCode project:
    cat << EOF > Podfile && platform :ios, '8.0' target 'QuickstartApp' do pod 'GoogleAPIClientForREST/Gmail', '~> 1.2.1' pod 'GoogleSignIn', '~> 4.1.1' end EOF pod install && open QuickstartApp.xcworkspace
  5. In the XCode Project Navigator select the project node "QuickstartApp" and select "QuickstartApp" in the TARGETS section, then select the Info tab, and expand the URL Types section.
  6. Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the credentials.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
  7. Rebuild the project by clicking Product > Clean Build Folder (while holding the option key) and Product > Build.

Step 3: Set up the sample



Replace the contents of the following files with the code provided:


AppDelegate.h:


#import <UIKit/UIKit.h>
@import GoogleSignIn;
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;

@end


AppDelegate.m


#import "AppDelegate.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Initialize Google sign-in.
    [GIDSignIn sharedInstance].clientID = @"<YOUR_CLIENT_ID>";

    return YES;
}
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {
    return [[GIDSignIn sharedInstance] handleURL:url
                               sourceApplication:sourceApplication
                                      annotation:annotation];
}

@end



ViewController.h


#import <UIKit/UIKit.h>
@import GoogleSignIn;
#import <GTLRGmail.h>
@interface ViewController : UIViewController <GIDSignInDelegate, GIDSignInUIDelegate>
@property (nonatomic, strong) IBOutlet GIDSignInButton *signInButton;
@property (nonatomic, strong) UITextView *output;
@property (nonatomic, strong) GTLRGmailService *service;

@end


ViewController.m


#import "ViewController.h"
@implementation ViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Configure Google Sign-in.
    GIDSignIn* signIn = [GIDSignIn sharedInstance];
    signIn.delegate = self;
    signIn.uiDelegate = self;
    signIn.scopes = [NSArray arrayWithObjects:kGTLRAuthScopeGmailReadonly, nil];
    [signIn signInSilently];

    // Add the sign-in button.
    self.signInButton = [[GIDSignInButton alloc] init];
    [self.view addSubview:self.signInButton];

    // Create a UITextView to display output.
    self.output = [[UITextView alloc] initWithFrame:self.view.bounds];
    self.output.editable = false;
    self.output.contentInset = UIEdgeInsetsMake(20.0, 0.0, 20.0, 0.0);
    self.output.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    self.output.hidden = true;
    [self.view addSubview:self.output];

    // Initialize the service object.
    self.service = [[GTLRGmailService alloc] init];
}
- (void)signIn:(GIDSignIn *)signIn
didSignInForUser:(GIDGoogleUser *)user
     withError:(NSError *)error {
    if (error != nil) {
        [self showAlert:@"Authentication Error" message:error.localizedDescription];
        self.service.authorizer = nil;
    } else {
        self.signInButton.hidden = true;
        self.output.hidden = false;
        self.service.authorizer = user.authentication.fetcherAuthorizer;
        [self fetchLabels];
    }
}
// Construct a query and get a list of labels from the user's gmail. Display the
// label name in the UITextView
- (void)fetchLabels {
    self.output.text = @"Getting labels...";
    GTLRGmailQuery_UsersLabelsList *query = [GTLRGmailQuery_UsersLabelsList queryWithUserId:@"me"];
    [self.service executeQuery:query
                      delegate:self
             didFinishSelector:@selector(displayResultWithTicket:finishedWithObject:error:)];
}
- (void)displayResultWithTicket:(GTLRServiceTicket *)ticket
             finishedWithObject:(GTLRGmail_ListLabelsResponse *)labelsResponse
                          error:(NSError *)error {
    if (error == nil) {
        NSMutableString *labelString = [[NSMutableString alloc] init];
        if (labelsResponse.labels.count > 0) {
            [labelString appendString:@"Labels:\n"];
            for (GTLRGmail_Label *label in labelsResponse.labels) {
                [labelString appendFormat:@"%@\n", label.name];
            }
        } else {
            [labelString appendString:@"No labels found."];
        }
        self.output.text = labelString;
    } else {
        [self showAlert:@"Error" message:error.localizedDescription];
    }
}

// Helper for showing an alert
- (void)showAlert:(NSString *)title message:(NSString *)message {
    UIAlertController *alert =
    [UIAlertController alertControllerWithTitle:title
                                        message:message
                                 preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *ok =
    [UIAlertAction actionWithTitle:@"OK"
                             style:UIAlertActionStyleDefault
                           handler:^(UIAlertAction * action)
     {
         [alert dismissViewControllerAnimated:YES completion:nil];
     }];
    [alert addAction:ok];
    [self presentViewController:alert animated:YES completion:nil];
}

@end


In the file AppDelegate.m, replace the placeholder <YOUR_CLIENT_ID> in with the client ID listed in credentials.plist.

Step 4: Run the sample

Switch to the scheme QuickstartApp and run the sample (Cmd+R) using the device simulator or a configured device. The first time you run the sample, it will prompt you to log in to your Google account and authorize access.
//***********************************************************************************
 

Step 1: Turn on the Gmail API

Click the button below to enable the API and download your credentials file. When prompted, ensure that you:
  • Select the platform iOS.
  • Enter com.example.QuickstartApp as the Bundle ID.
  • Download the client configuration file credentials.plist.
You Can Enable API :-    CLICK HERE

Step 2: Prepare the workspace

  1. Open Xcode and create a new project:
    1. Click File > New > Project, select the iOS > Application > Single View Application template, and clickNext.
    2. Set the Product Name to "QuickstartApp", Organization Identifier to "com.example", and Language toSwift . Click Next.
    3. Select a destination directory for the project and click Create.
  2. Close the project by clicking File > Close Project.
  3. Open a Terminal window and navigate to the directory that contains the QuickstartApp.xcodeproj file you just created.
  4. Run the following commands to create the Podfile, install the library, and open the resulting XCode project:
    cat << EOF > Podfile && platform :ios, '8.0' use_frameworks! target 'QuickstartApp' do pod 'GoogleAPIClientForREST/Gmail', '~> 1.2.1' pod 'GoogleSignIn', '~> 4.1.1' end EOF pod install && open QuickstartApp.xcworkspace
  5. In the XCode Project Navigator select the project node "QuickstartApp" and select "QuickstartApp" in the TARGETS section, then select the Info tab, and expand the URL Types section.
  6. Click the + button, and add a URL scheme for your reversed client ID. To find this value, open the credentials.plist configuration file, and look for the REVERSED_CLIENT_ID key. Copy the value of that key, and paste it into the URL Schemes box on the configuration page. Leave the other fields blank.
  7. Rebuild the project by clicking Product > Clean Build Folder (while holding the option key) and Product > Build.


Step 3: Set up the sample

Replace the contents of the following files with the code provided:



AppDelegate.swift


import GoogleSignIn
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func applicationDidFinishLaunching(_ application: UIApplication) {
        // Initialize Google sign-in.
        GIDSignIn.sharedInstance().clientID = "<YOUR_CLIENT_ID>"
    }

    func application(_ application: UIApplication,
                     open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication: sourceApplication,
                                                 annotation: annotation)
    }

    @available(iOS 9.0, *)
    func application(_ app: UIApplication, open url: URL,
                     options: [UIApplicationOpenURLOptionsKey : Any]) -> Bool {
        let sourceApplication = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
        let annotation = options[UIApplicationOpenURLOptionsKey.annotation]
        return GIDSignIn.sharedInstance().handle(url,
                                                 sourceApplication: sourceApplication,
                                                 annotation: annotation)
    }
}



ViewController.swift




import GoogleAPIClientForREST
import GoogleSignIn
import UIKit
class ViewController: UIViewController, GIDSignInDelegate, GIDSignInUIDelegate {

    
    // If modifying these scopes, delete your previously saved credentials by
    // resetting the iOS simulator or uninstall the app.
    private let scopes = [kGTLRAuthScopeGmailReadonly]

    private let service = GTLRGmailService()
    let signInButton = GIDSignInButton()
    let output = UITextView()

    override func viewDidLoad() {
        super.viewDidLoad()

        // Configure Google Sign-in.
        GIDSignIn.sharedInstance().delegate = self
        GIDSignIn.sharedInstance().uiDelegate = self
        GIDSignIn.sharedInstance().scopes = scopes
        GIDSignIn.sharedInstance().signInSilently()

        // Add the sign-in button.
        view.addSubview(signInButton)

        // Add a UITextView to display output.
        output.frame = view.bounds
        output.isEditable = false
        output.contentInset = UIEdgeInsets(top: 20, left: 0, bottom: 20, right: 0)
        output.autoresizingMask = [.flexibleHeight, .flexibleWidth]
        output.isHidden = true
        view.addSubview(output);
    }

    func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!,
              withError error: Error!) {
        if let error = error {
            showAlert(title: "Authentication Error", message: error.localizedDescription)
            self.service.authorizer = nil
        } else {
            self.signInButton.isHidden = true
            self.output.isHidden = false
            self.service.authorizer = user.authentication.fetcherAuthorizer()
            fetchLabels()
        }
    }

    // Construct a query and get a list of upcoming labels from the gmail API
    func fetchLabels() {
        output.text = "Getting labels..."

        let query = GTLRGmailQuery_UsersLabelsList.query(withUserId: "me")
        service.executeQuery(query,
                             delegate: self,
                             didFinish: #selector(displayResultWithTicket(ticket:finishedWithObject:error:))
        )
    }

    // Display the labels in the UITextView
    func displayResultWithTicket(ticket : GTLRServiceTicket,
                                 finishedWithObject labelsResponse : GTLRGmail_ListLabelsResponse,
                                 error : NSError?) {
        if let error = error {
            showAlert(title: "Error", message: error.localizedDescription)
            return
        }
        var labelString = ""
        if let labels = labelsResponse.labels, labels.count > 0 {
            labelString += "Labels:\n"
            for label in labels {
                labelString += "\(label.name!)\n"
            }
        } else {
            labelString = "No labels found."
        }
        output.text = labelString
    }


    // Helper for showing an alert
    func showAlert(title : String, message: String) {
        let alert = UIAlertController(
            title: title,
            message: message,
            preferredStyle: UIAlertControllerStyle.alert
        )
        let ok = UIAlertAction(
            title: "OK",
            style: UIAlertActionStyle.default,
            handler: nil
        )
        alert.addAction(ok)
        present(alert, animated: true, completion: nil)
    }
}


In the file AppDelegate.swift, replace the placeholder <YOUR_CLIENT_ID> in the copied code with the client ID listed in credentials.plist.


Step 4: Run the sample

Switch to the scheme QuickstartApp and run the sample (Cmd+R) using the device simulator or a configured device. The first time you run the sample, it will prompt you to log in to your Google account and authorize access.