GooglePlus Integration in ios - ios

I already successfully integrated Google+ to my iOS app. But with the latest Apple store updates, the app is not allowed to open the browser to initiate the Google authentication using safari so i tried uiwebview for googleplus authentication and i am getting the access token but i cannot able to get the username and email address of the person logged in.Below i added my source,
NSString *client_id = #"***************************";;
NSString *secret = #"*******************************";
NSString *callbakc = #"https://www.example.com/oauth2callback";;
NSString *scope = #"https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/reader/api/0/subscription";
NSString *visibleactions = #"http://schemas.google.com/AddActivity";
#interface MainViewController ()
#end
#implementation MainViewController
#synthesize webview,isLogin,isReader;
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",client_id,callbakc,scope,visibleactions];
[webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
NSLog(#"dgfduiussdiff %# ",[[request URL] host]);
if ([[[request URL] host] isEqualToString:#"www.example.com"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSError* error;
[receivedData appendData:data];
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:receivedData
options:kNilOptions
error:&error];
NSLog(#"verifier %#",json);
}
- (void)connection:(NSURLConnection *)connection didFailWithError: (NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
After executing the above source i getting the below response printed in nslog,
verifier 4/kMcSZ2l-d_XXPo24NSdsMnugoP_MGDGPP4D5C1LRTfY
2015-07-21 18:04:16.103 TechnoGerms.com[8981:189233] verifier {
"access_token" = "ya29.twG9kyMElyC8BgAxujF98WKN0BQ246Ey6zsKQEgSpKsNEb5JOS3QRl12La6XBy1geZnL";
"expires_in" = 3600;
"id_token" = "eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg";
"token_type" = Bearer;
}
How i can get the username and email of person logged in by using the access token which i got above ? Please give any suggestions as i dont get any solution on google.
Thanks for your support

if you want to fetch the whole profile of the google+ user, you can use the below URL
https://www.googleapis.com/plus/v1/people/me/?access_token={YOUR_ACCESS_TOKEN}
Then call the GET method. You will be given by an array containing authorized profile details.
Another method is that, if you want to store the authorized users email, its already present in the field as id_token. It is a base64_encoded data with some fields. If you decode the id yo will get some information about the user.For example in your result you found id_token as
eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ.eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg
The above id_token contains 2 parts separated by '.'. The first part is thebase64_encoded key and the second part is metadata.
you can decode both the data as
$key=base64_decode(eyJhbGciOiJSUzI1NiIsImtpZCI6ImRhNjYyNWIzNmJjMDlkMzAwMzUzYjI4YTc0MWNlMTc1MjVhNGMzM2IifQ)
will give you the key
$data=base64_decode(eyJpc3MiOiJhY2NvdW50cy5nb29nbGUuY29tIiwic3ViIjoiMTE0MjE4NDEwODI0NzM1ODkyMDg0IiwiYXpwIjoiMTY5NzY2MjI4OTY4LWtoNzI1dTFpZWdzNHN1bnFhOThhcHUxMHU4djhhcmFmLmFwcHMuZ29vZ2xldXNlcmNvbnRlbnQuY29tIiwiZW1haWwiOiJhcmp1bkBsaW5rd2FyZS5pbiIsImF0X2hhc2giOiJQVnJxTURpNDViZnVGTm9kTmlsSFlRIiwiZW1haWxfdmVyaWZpZWQiOnRydWUsImF1ZCI6IjE2OTc2NjIyODk2OC1raDcyNXUxaWVnczRzdW5xYTk4YXB1MTB1OHY4YXJhZi5hcHBzLmdvb2dsZXVzZXJjb250ZW50LmNvbSIsImhkIjoibGlua3dhcmUuaW4iLCJpYXQiOjE0Mzc0ODIwNTUsImV4cCI6MTQzNzQ4NTY1NX0.uSMrV8rOz4T4i5MhiCeQueNVGLv4NBLP-gtOcyow8t4BY9qvUO78sG4y0jPhbclPdX1kUZjzMVTeah2nU9fTYyl50dlj5FzWNy7LyM-a1GC2jEwkgWMgHdRPh6l7dqMrjQ9sU1rF-ZaiWfG7C9VJTJ76uEWRiSKKA9EFQtBil3xBtmDH07UMRxkbri2jBwaCPAWgjU8-dTarrxNESrwrO_nptaRzfGeaTyQBIYCAk6_9deXmblPgteER1OHoa65xb1OVK3ZPeZ3_dj9gjlXSyGp2ho5WIFGf2xRvW4XoROpUYqhLvrS3s-YrrZ8J5X5-3mafrs1qDjJYJogctbW7dg)
will give you the metadata.
while decoding the data ,it will give the result as
{"iss":"accounts.google.com","sub":"114218410824735892084","azp":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","email":"arjun#linkware.in","at_hash":"PVrqMDi45bfuFNodNilHYQ","email_verified":true,"aud":"169766228968-kh725u1iegs4sunqa98apu10u8v8araf.apps.googleusercontent.com","hd":"linkware.in","iat":1437482055,"exp":1437485655}
Above result you can find the email filed. I hope this will help you.

Related

My app is asking for permission to “Have offline access”, why?

My app is asking for permission to “Have offline access”, why? It's the weirdest thing. I've done a bit of searching and haven't really found anything that's worked. I've tried using these for scopes:
https://www.googleapis.com/auth/plus.profile.emails.read
https://www.googleapis.com/auth/plus.login
and that didn't seem to help.
Below is a screenshot and some of my code to help you see what's going on:
Some of my code:
#import "ViewController.h"
NSString *callbakc = #"http://localhost/";
NSString *client_id = #“CLIENT ID“;
NSString *scope = #"https://www.googleapis.com/auth/userinfo.email+https://www.googleapis.com/auth/userinfo.profile+https://www.google.com/reader/api/0/subscription";
NSString *secret = #“SECRET”;
NSString *visibleactions = #"http://schemas.google.com/AddActivity";
#interface ViewController () {
NSString *authAccessToken;
UIAlertController *alertController;
}
#property (strong, nonatomic) NSMutableData *receivedData;
#property (weak, nonatomic) IBOutlet UIWebView *webView;
#end
#implementation ViewController
#pragma mark - Lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",client_id,callbakc,scope,visibleactions];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10];
[_webView loadRequest:request];
}
#pragma mark - WebView Delegate
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
[self performSelector:#selector(progressDelay:) withObject:nil afterDelay:0.0];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
if (![param isEqualToString:#"error=access_denied"]) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
// NSLog(#"verifier %#",verifier);
break;
}
}
else {
[self.navigationController popViewControllerAnimated:NO];
}
}
if (!verifier==0) {
[self showAlertViewWithTitle:#"" message:#"Please wait" okAction:NO];
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,client_id,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPShouldHandleCookies:NO];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"Connection: %#", theConnection);
self.receivedData = [[NSMutableData alloc] init];
}
else {
// cancel button click
NSLog(#"not Verified!!");
}
return NO;
}
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
// show progress
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
[alertController dismissViewControllerAnimated:YES completion:nil];
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {
if (error.code==102) //Frame load interrupted
return;
[alertController dismissViewControllerAnimated:YES completion:nil];
[self showAlertViewWithTitle:#"Error" message:[error localizedDescription] okAction:YES];
}
#pragma mark - NSURLConnection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
[self showAlertViewWithTitle:#"Error" message:[NSString stringWithFormat:#"%#", error] okAction:YES];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *response = [[NSString alloc] initWithData:self.receivedData encoding:NSUTF8StringEncoding];
NSData *data = [response dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *tokenData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
if ([tokenData objectForKey:#"access_token"]) {
authAccessToken = [tokenData objectForKey:#"access_token"];
[self getUserInfo:authAccessToken];
}
else {
[alertController dismissViewControllerAnimated:YES completion:nil];
NSLog(#"RESULT: %#", tokenData);
[self showAlertViewWithTitle:[tokenData objectForKey:#"name"] message:[NSString stringWithFormat:#"%#", tokenData] okAction:YES];
// Flush all cached data
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
#pragma mark - Private Method Implementation
-(void)getUserInfo:(NSString *)token {
NSString *url = [NSString stringWithFormat:#"https://www.googleapis.com/oauth2/v1/userinfo?access_token=%#",token];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"GET"];
[request setHTTPShouldHandleCookies:NO];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
NSLog(#"Connection: %#", theConnection);
self.receivedData = [[NSMutableData alloc] init];
}
-(void)progressDelay:(id)sender {
// Dismiss progress
}
#end
Any help would be greatly appreciated!
Thank you
This is from https://stackoverflow.com/questions/32210920/why-is-my-app-asking-for-permission-to-have-offline-access?answertab=oldest#tab-top:
This is normal behavior and occurs when the user has granted
permission already.
Basically, no need to worry about it unless you really don't want that
showing up, in that case, you need to un auth the users old token
before requesting a new one.
I'm not exactly sure how because I haven't done this before, but before you authorize a new token you need to un-authorize the old one.
You'll need to modify the -(void)getUserInfo:(NSString *)token method.
For some reason unknown to me. The email scope pops up with
Have offline access
If you want to remove the have offline access remove the email scope. Personally I think it is miss leading to users that you are asking for email access yet are prompted for offline access. Technically speaking all OAuth2 that returns a refresh token gives offline access so the user should always be told that you are getting offline access but it doesnt.

I have integrated google plus in my IOS App , Now how can i get profile detail of logged in user?

I have integrated google plus in my ios app ,I am able to get access token.I have used authentication flow to integrate google plus.So now after getting access token how can i get user profile details like username, email id, profile pic etc?
My code to get access token is as below:
-(IBAction)btnGooglePlusClicked:(UIButton *)sender
{
IBwebView.hidden = FALSE;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CALL_BACK_URL,GOOGLE_PLUS_SCOPE,GOOGLE_PLUS_VISIBLE_ACTIONS];
[IBwebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
// [indicator startAnimating];
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,GOOGLE_PLUS_CLIENT_ID,GOOGLE_PLUS_CLIENT_SECRET,GOOGLE_PLUS_CALL_BACK_URL];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
return YES;
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error"
message:[NSString stringWithFormat:#"%#", error]
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *response = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
SBJsonParser *jResponse = [[SBJsonParser alloc]init];
NSDictionary *tokenData = [jResponse objectWithString:response];
// WebServiceSocket *dconnection = [[WebServiceSocket alloc] init];
// dconnection.delegate = self;
NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#", [tokenData objectForKey:#"refresh_token"], self.isLogin];
// NSString *pdata = [NSString stringWithFormat:#"type=3&token=%#&secret=123&login=%#",[tokenData accessToken.secret,self.isLogin];
// [dconnection fetch:1 withPostdata:pdata withGetData:#"" isSilent:NO];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Google Access TOken"
message:pdata
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
I feel the the method you are using will not help to get the profile detail.
I suggest to use the proper method which ensures the best results.
Please check this out : https://developers.google.com/+/mobile/ios/
This will surely help you to get required outcome.

How to get user information in Google plus integration with iOS

Hi I am integrating google plus integration I want to fetch user information who is currently login. I am able to get token after login but I don't know how to get personal information.
I am login step by step as following this is only because I want to get login without open external browser.
Open url link in UIWebView which open login screen in View Did Load.
UIWebView * webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
webView.tag=99;
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/auth?response_type=code&client_id=%#&redirect_uri=%#&scope=%#&data-requestvisibleactions=%#",[GPPSignIn sharedInstance].clientID,callbakc,scope,visibleactions];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
[self.view addSubview:webView];
Get call for token Login
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
if ([[[request URL] host] isEqualToString:#"localhost"]) {
// Extract oauth_verifier from URL query
NSString* verifier = nil;
NSArray* urlParams = [[[request URL] query] componentsSeparatedByString:#"&"];
for (NSString* param in urlParams) {
NSArray* keyValue = [param componentsSeparatedByString:#"="];
NSString* key = [keyValue objectAtIndex:0];
if ([key isEqualToString:#"code"]) {
verifier = [keyValue objectAtIndex:1];
NSLog(#"verifier %#",verifier);
break;
}
}
if (verifier) {
NSString *data = [NSString stringWithFormat:#"code=%#&client_id=%#&client_secret=%#&redirect_uri=%#&grant_type=authorization_code", verifier,[GPPSignIn sharedInstance].clientID,secret,callbakc];
NSString *url = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[data dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self];
receivedData = [[NSMutableData alloc] init];
} else {
// ERROR!
}
[webView removeFromSuperview];
return NO;
}
and I get the response in did recieve data
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
[receivedData appendData:data];
NSLog(#"verifier %#",receivedData);}
Now after token I want to call for fetch user information who is login, Kindly guide me on this how can I achieve this target, this will be great for me.
Thanks.

Adding Multiple GET Requests to NSMutableArray in iOS App

The app keeps score during a game. Based off of your score, it will retrieve a quote from an online database, using a GET method and returning it in JSON format. For example, your score is 5, you get 1 quote, 10, you get 2 and so on. The view that shows the quote(s) is a UIViewController with a UITextView in it.
I have a for loop that runs based off the score, to run the same GET request over and over again, after a 1.5 second delay so the server housing the database won't reject requests made nearly simultaneously.
I create a few NSStrings and pull information from the JSON data, append it into some basic HTML code and then set that as the UITextView attributedText.
Most of the time this runs great, but every once in a while, I'll expect 2 quotes, and only get 1, or some of the quotes will wind up being the same.
Can someone tell me if there is a better way to go about doing this than how I currently am?
- (void)viewWillAppear:(BOOL)animated {
if ([textView.text isEqualToString:#""]) {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSInteger getReady = [defaults integerForKey:#"after"];
self.theNumber = getReady;
for(int i = 0; i< self.theNumber; i++) {
[self performSelector:#selector(quoteView) withObject:self afterDelay:1.5 ];
}
}
}
-(void) quoteView {
NSString *bringitalltogether = #"http://url.com&type=json";
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:bringitalltogether]
cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
[request setHTTPMethod:#"GET"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*) response;
if (code == 200){
}
else
{
UIAlertView *oops = [[UIAlertView alloc] initWithTitle:#"Oops" message:#"The network is having difficulties getting you the quote. Please check your network settings and try again later." delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil];
[oops show];
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableDictionary *allResults = [NSJSONSerialization
JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
NSArray *book = [allResults valueForKey:#"bookname"];
self.bookstring = [book objectAtIndex:0];
NSArray *chapter = [allResults valueForKey:#"chapter"];
self.chapterstring = [chapter objectAtIndex:0];
NSArray *verse = [allResults valueForKey:#"verse"];
self.versestring = [verse objectAtIndex:0];
NSArray *text = [allResults valueForKey:#"text"];
self.textstring = [text objectAtIndex:0];
[self doneGotIt];
}
- (void) doneGotIt {
if (!self.theArray) {
self.theArray = [[NSMutableArray alloc] init];
}
NSString *doIt = [NSString stringWithFormat:#"%# - %# %#:%#", self.textstring, self.bookstring, self.chapterstring, self.versestring];
[self.theArray addObject:doIt];
NSString *theEnd = [self.theArray componentsJoinedByString:#"\n"];
NSString *loadHTML = [#"<head> <style type='text/css'>a > img {pointer-events: none;cursor: default;}</style></head><b><div align=\"left\"><font size=5>" stringByAppendingString:theEnd];
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[loadHTML dataUsingEncoding:NSUnicodeStringEncoding] options:#{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
textView.attributedText = attributedString;
NSLog(#"ARRAY: %#", self.theArray);
NSLog(#"String: %#", theEnd);
}
-(IBAction)finished {
[self dismissViewControllerAnimated:YES completion:nil];
textView = nil;
}
From the NSLogs I have towards the end there, sometimes the NSMutableArray contains several of the same quotes, which is why they don't show in the string, because it eliminates duplicates. My question is if there is a better way to do this that will keep these errors from occurring?
Here is some pseudo code for you
mutableArray = new NSMutableArray
while([mutableArray count] < total) {
quote = getQuote()
if([array indexOfObject:quote] != NSNotFound)
[mutableArray addObject:quote]
}
This will ensure you do not have duplicate quotes. After you have an array of valid quotes, you can then construct the string exactly how you want it.

AFNetworking - Download File, unexpected message format 'Raw'

I am basically trying to download a file which can be from a PDF to a PNG. I am using AFNetworking 1.x.
However, I am getting an error:
NSURL *baseURL = [NSURL URLWithString:#"https://myserver.com/webservices/Services/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:baseURL];
//NSLog(#"Formatted URL: %#", formattedURL);
//NSMutableURLRequest *photoRequest = [NSMutableURLRequest requestWithURL:url];
NSMutableDictionary *parameters = [[NSMutableDictionary alloc] init];
[httpClient defaultValueForHeader:#"Accept"];
[httpClient setParameterEncoding:AFFormURLParameterEncoding];
[parameters setObject:[NSNumber numberWithInteger:#"10772"] forKey:#"FileId"];
[parameters setObject:[NSNumber numberWithBool:YES] forKey:#"requireUnCompression"];
NSMutableURLRequest *fileRequest = [httpClient requestWithMethod:#"POST" path:#"FileService.svc/DownloadFile" parameters:parameters];
//[fileRequest setHTTPBody:<#(NSData *)#>]
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:fileRequest];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"Successss!");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Failed: %#", [operation error]);
}];
[httpClient enqueueHTTPRequestOperation:operation];
However, I am getting an error:
Failed: Error Domain=AFNetworkingErrorDomain Code=-1011 "Expected status code in (200-299), got 400" UserInfo=0x12112770 {NSLocalizedRecoverySuggestion={"faultType":"InvalidOperationException","message":"The incoming message has an unexpected message format 'Raw'. The expected message formats for the operation are 'Xml', 'Json'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details."}, AFNetworkingOperationFailingURLRequestErrorKey=<NSMutableURLRequest: 0xc865c40> { URL: https://myserver.com/webservice/Services/FileService.svc/DownloadFile }, NSErrorFailingURLKey=https://myserver.com/webservices/Services/FileService.svc/DownloadFile, NSLocalizedDescription=Expected status code in (200-299), got 400, AFNetworkingOperationFailingURLResponseErrorKey=<NSHTTPURLResponse: 0xc8696a0> { URL: https://myserver.com/webservices/Services/FileService.svc/DownloadFile } { status code: 400, headers {
"Cache-Control" = private;
"Content-Length" = 327;
"Content-Type" = "application/xml; charset=utf-8";
Date = "Thu, 17 Oct 2013 19:45:07 GMT";
"Persistent-Auth" = true;
Server = "Microsoft-IIS/8.0";
"X-AspNet-Version" = "4.0.30319";
"X-Powered-By" = "ASP.NET";
} }}
Thank you in advance!
I download PDFs/Images/WordDocs in my app without AFNetworking, I also ran into issues, so I decided to just good old NSURLConnection. My NSURLRequest does not use POST data, but I modified the NSURLRequest in here for POST data.
Once the file is done downloading, I present a QLPreviewController to display it. (this can handle displaying PDFs, images, or word docs. It requires a bit more code if youd like to see that as well)
Declare 4 properties in your .h:
#property (strong, nonatomic) NSNumber *reportLength;
#property (strong, nonatomic) NSURLConnection *reportConnection;
#property (strong, nonatomic) NSMutableData *reportData;
#property (strong, nonatomic) NSString *reportURL;
also add NSURLConnectionDelegate to your delegate list
Then in the .m:
- (void)downloadReport:(NSString *)reqUID
{
NSString *file = [NSString stringWithFormat:#"%#GetReport.ashx?requestUID=%#&deviceUID=%#&token=%#", _globals.baseURL, reqUID, [MySingleton getDeviceID], _globals.token];
NSURL *fileURL = [NSURL URLWithString:file];
NSMutableURLRequest *req = [NSURLRequest requestWithURL:fileURL];
[req setHTTPMethod:#"POST"];
NSString *postString = #"FileID=10772&requireUnCompression=1";
[req setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
_reportConnection = [NSURLConnection connectionWithRequest:req delegate:self];
_reportData = [NSMutableData data];
[_reportConnection start];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[_reportData setLength:0];
NSLog(#"didReceiveResponse %#: %#", [response URL], [(NSHTTPURLResponse*)response allHeaderFields]);
_reportLength = [NSNumber numberWithLongLong:[response expectedContentLength]];
if(_reportLength.longLongValue == 0)
{
[_reportConnection cancel];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Empty Report" message:#"The report you requested is empty. " delegate:self cancelButtonTitle:#"Ok" otherButtonTitles: nil, nil];
[alert show];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[_reportData length]];
[_reportData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSString *msg = [NSString stringWithFormat:#"Error"];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"There was an issue downloading the attachment. Please try again." message:msg delegate:self cancelButtonTitle:#"Not Now" otherButtonTitles: #"Yes", nil];
[alert show];
}
//when finished save in documents directory
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSArray *dirArray = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
_reportURL = [NSString stringWithFormat:#"%#/%#", [dirArray objectAtIndex:0], [NSString stringWithFormat:#"%#.pdf", _currentRequestUID]];
NSError *err;
if ([_reportData writeToFile:_reportURL options:NSAtomicWrite error:&err] == NO) {
NSLog(#"writeToFile error: %#", _reportURL);
NSString *msg = [NSString stringWithFormat:#"There was an issue saving the attachment. Please try again."];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:msg delegate:self cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[alert show];
}
else //pdf downloaded, display using QLPreviewController
{
NSLog(#"Written: _reportURL: %#", _reportURL);
QLPreviewController *previewController=[[QLPreviewController alloc]init];
previewController.delegate=self;
previewController.dataSource=self;
UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:#"Close" style:UIBarButtonItemStylePlain target:self action:#selector(btnCloseQLTouch:)];
[previewController.navigationItem setLeftBarButtonItems:[NSArray arrayWithObjects:btn, nil]];
[self presentViewController:previewController animated:YES completion:nil];
}
}
EDIT
To get the QLPreviewController working first add the <QuickLook.framework> to your project, then add these deletages in your .h:
QLPreviewControllerDataSource, QLPreviewControllerDelegate
Here are the datasource/delegate methods needed to display the file:
//quicklook datasource/ delegate
- (NSInteger) numberOfPreviewItemsInPreviewController: (QLPreviewController *) controller
{
return 1;
}
- (id <QLPreviewItem>)previewController: (QLPreviewController *)controller previewItemAtIndex:(NSInteger)index
{
return [NSURL fileURLWithPath:_reportURL];
}

Resources