Friday, May 31, 2013

Google+ Integration in IOS from scratch

Google+ Integration in IOS

In this post i am going to show you steps to integrate google+ in our IOS Application.

Prerequisites


Adding Google+ client features to iOS applications requires:



Step 1. Creating the APIs Console project

To enable the Google+ API for your app, you need to create an APIs Console project, enable the Google+ API then create and get a client ID.

  1. In the Google APIs Console , select Create from the pull-down menu on the left, enter a project name (such as "iOS App"), and click the Create project button.
  2. In the Services pane, enable the Google+ API and any other APIs that your app requires by turning them on. If you plan to use other APIs, turn those on as well.
  3. In the API Access pane, click Create an OAuth 2.0 Client ID.
    1. In the Product name field, enter a name for your application (such as "Sample"), and click Next. Providing a product logo is optional.
    2. In the Create Client ID dialog box, shown below, do the following:
      • Select Installed application for the Application type.
      • Select iOS.
      • In the Bundle ID field, enter the bundle identifier from your application's project summary. If you are using the provided sample app, usecom.google.GooglePlusSample.
      • If your app is published in the Apple iTunes App Store, enter your app's App Store identifier in the App Store ID field. You can determine the ID from the "id" part of your app's URL on iTunes website: http://itunes.apple.com/us/app/id<YOUR_APP_STORE_ID>
      • (Optional) If you plan to build deep linking into shared posts made from your app, enable Deep Linking.
      • Click the Create client ID button.
      • Shows options in the Create Client ID dialog box.
  4. In the API Access pane, locate the section Client ID for installed applications and note or copy the Client ID that you will need later to run the sample

Step 2.  Initialize the Google+ Client in your Project


Initializing the client sets up your project with the minimal settings. Depending on your app's needs, you will further configure your project to handle signing in with Google+, sharing, and writing app activities to Google.

  1. Include the following frameworks in your Xcode project:
    • SystemConfiguration.framework
    • Security.framework
  2. Drag and drop the following frameworks from the SDK into your XCode project:
    • GooglePlus.framework
    • GoogleOpenSource.framework
    If your project already includes some of the open source files, you can instead include the remaining files from the OpenSource folder.
  3. If you plan to use the sign-in button provided by the SDK, include the GooglePlus.bundle in your XCode project to add it to your target.
  4. Add the ObjC linker flag to the app target's build settingss:
    Other Linker Flags: -ObjC
    
  5. In your app's controller, set your client ID:
    static NSString * const kClientId = @"YOUR_CLIENT_ID";
    

Step 3: Add URL type


In your app's Info tab, add a URL type and enter your bundle 
ID as the identifier and scheme: 



 Step 4:Google+ Sign-In for iOS




The Google+ Sign-In button manages the OAuth 2.0 flow and token lifecycle, simplifying your integration with the Google APIs. Furthermore, if the user has the native Google+ mobile app installed, the Google+ SDK also automatically integrates with it, so users will not have to re-enter their Google credentials to authorize your app.

Enable sign in

To enable sign in, you must configure the GPPSignIn shared singleton instance. You can do this in many places in your app. The easiest place is often to configure this instance in your view controller's viewDidLoad method.
  1. In your view controller's .h file, import GooglePlus/GooglePlus.h, and declare that this class implements the GPPSignInDelegate protocol.

    #import <GooglePlus/GooglePlus.h>
    @interface RkViewController : UIViewController <GPPSignInDelegate>
    static NSString * const kClientId = @"YOUR_CLIENT_ID";
  2. In your view controller's .m file, import GoogleOpenSource/GoogleOpenSource.h.

     #import <GoogleOpenSource/GoogleOpenSource.h>
  3. In your view controller's viewDidLoad method, configure the GPPSignIn shared singleton instance by declaring its client ID, delegate, and scopes.

    - (void)viewDidLoad{
      [super viewDidLoad];
    GPPSignIn *signIn = [GPPSignIn sharedInstance];
    // You previously set kClientID in the "Initialize the Google+ client" step
    signIn.clientID = kClientID;
    signIn.scopes = [NSArray arrayWithObjects:
                       kGTLAuthScopePlusLogin,@"https://www.googleapis.com/auth/userinfo.email" // defined in GTLPlusConstants.h
                       nil];
      signIn.delegate = self;
    }
  4. Implement the GPPSignInDelegate in the view controller to handle the sign-in process by defining the following method.

    - (void)finishedWithAuth: (GTMOAuth2Authentication *)auth  error: (NSError *) error{
        NSLog(@"Received error %@ and auth object %@",error, auth);
    }
  5. In your app delegate .m file, and import GooglePlus/GooglePlus.h.
    #import <GooglePlus/GooglePlus.h>
    
  6. Call the GPPURLHandler URL handler from your app delegate's URL handler. This handler will properly handle the URL that your application receives at the end of the authentication process.


    - (BOOL)application: (UIApplication *)application
                openURL: (NSURL *)url
      sourceApplication: (NSString *)sourceApplication
             annotation: (id)annotation {
     return [GPPURLHandler handleURL:url
                   sourceApplication:sourceApplication
                          annotation:annotation];
    }
    Tip: If you wish to test up to this point, you can call [signIn authenticate] at the end of your `viewDidLoad` method. The application will redirect you to a sign-in dialog at startup

Add the sign-in button

Next, you will add the Google+ Sign-In button so that the user can initiate the sign-in process.
  1. If you added the test code [signIn authenticate] from the previous section, remove that code from your viewDidLoad controller.
  2. In your view controller's .h file, add the forward class declaration for the GPPSignInButton.
    @class GPPSignInButton;
    
  3. Also in your view controller's .h file, declare the sign-in button as a property.
    @property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;
    
  4. In your view controller's .m file, import the header files for the Google+ Sign-In button.
    #import <GooglePlus/GooglePlus.h>
    
  5. Synthesize the GPPSignInButton property if necessary, although this step should no longer be required in newer versions of Xcode.
    @synthesize signInButton;
    
  6. Add the GPPSignInButton to your storyboard, XIB file, or instantiate it programmatically. GPPSignInButton inherits from UIButton, so if you are using a storyboard or XIB file, you can drag a Round Rect Button or View onto your view controller and set its Custom Class to GPPSignInButton.
  7. Connect the button it to the signInButton property of your view controller.
Next, you can implement and handle automatic signing in of the user.

Automatically sign in the user

If you run your app at this point, you will be able to use the Google+ sign-in button to sign in to the app. You might also notice that after your first sign in, subsequent sign-in attempts succeed "silently" without any disruption to your app.
The GPPSignIn class has a trySilentAuthentication method that attempts to automatically sign in the user. This call succeeds if the user has authorized your application in the past, they haven't revoked access to your application, and the app isn't requesting new scopes since they last signed in. If this call succeeds, it calls yourfinishedWithAuth:error: method when sign in is complete.
Add the [signIn trySilentAuthentication] call to the end of your viewDidLoad method.

Final step: To get Logged user Profile info

- (void)finishedWithAuth:(GTMOAuth2Authentication *)auth
                   error:(NSError *)error {
    if (error) {
        self.SigninAuthStatus.text =
        [NSString stringWithFormat:@"Status: Authentication error: %@", error];
        return;
    }
 // getting the access token from auth
   NSString  *accessTocken = [auth valueForKey:@"accessToken"]; // access tocken pass in .pch file
    [accessTocken retain];
    NSLog(@"%@",accessTocken);
NSString *str=[NSString stringWithFormat:@"https://www.googleapis.com/oauth2/v1/userinfo?access_token=%@",accessTocken];
NSString *escapedUrl = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@",escapedUrl]];
    NSString *jsonData = [[NSString alloc] initWithContentsOfURL:url usedEncoding:nil error:nil];
    NSDictionary *jsonDictionary = [NSJSONSerialization JSONObjectWithData:[jsonData dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableContainers error:&error];
   // NSMutableDictionary *proDic = [[NSMutableDictionary alloc] init];
    NSString *userId=[jsonDictionary objectForKey:@"id"];
   // proDic=[jsonData JSONValue];
    NSLog(@" user deata %@",jsonData);
    NSLog(@"Received Access Token:%@",auth);
   // NSLog(@"user google user id  %@",signIn.userEmail); //logged in user's email id
    
    //
    GTLServicePlus* plusService = [[[GTLServicePlus alloc] init] autorelease];
    plusService.retryEnabled = YES;
   [plusService setAuthorizer:auth];
    GTLQueryPlus *query = [GTLQueryPlus queryForPeopleGetWithUserId:userId];
    
    [plusService executeQuery:query completionHandler:^(GTLServiceTicket *ticket,GTLPlusPerson *person,NSError *error) {
                if (error) {
                    GTMLoggerError(@"Error: %@", error);
                } else {
                    // Retrieve the display name and "about me" text
                    [person retain];
                    NSString *description = [NSString stringWithFormat:
                                             @"%@\n%@", person.displayName,
                                             person.aboutMe];
                    GTLPlusPersonImage *image  =person.image;
                    NSString *strimag=[image valueForKey:@"url"];
                    
                   // [self setImageFromURL:[NSURL URLWithString:strimag]];
                    NSData *receivedData = [NSData dataWithContentsOfURL:[NSURL URLWithString:strimag]];
                    
                    UIImage *img = [[UIImage alloc] initWithData:receivedData ];
                    receivedData=UIImageJPEGRepresentation(img,50);
                   UIImage *img1=[UIImage imageWithData:receivedData];
                    self.imageView.image = img1;
                   // UIImage *image=[UIImage]
                   // self.imageView.image=imgage;
                    NSLog(@"hai in person Image %@",image);
                    NSLog(@"description %@",description);
                }
            }];
   // [self reportAuthStatus];
    [[GPPSignIn sharedInstance] signOut];

}













1 comment:

  1. Hi i am getting error 400 redirect_uri_mismatch if u have sample project done with u pls share me @ p.saikrishna@outlook.com

    ReplyDelete