Google oauth 2.0 refreshing access token - iphone

How to get a new access token in Google Oauth 2.0?
I tried this:
NSString * urlString1 = [NSString stringWithFormat:#"https://accounts.google.com/o/oauth2/token?client_id=my_client_id&client_secret=my_client_secret&refresh_token=%#&grant_type=refresh_token",auth.refreshToken];
NSURL * url = [NSURL URLWithString:urlString1];
NSMutableURLRequest * request = [[NSMutableURLRequest alloc] initWithURL:url];
[request addValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
NSURLConnection * connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
But result is: Method Not Allowed (Error 405)
Maybe there is another way to get new access token?
Please help!
Thanks!

HTTP 405 means that you are trying to use a verb that is not allowed by the resource. For example using a POST on a read-only GET resource or PUT on a write resource that only accepts POSTs.
See abraham's answer : Google with oauth 2

please use following code to get access token in Google Plus
First Replase you - (NSString *)description method in GTMOAuth2Authentication.h file and you will surely get G+ Acccess token
- (NSString *)description
{
NSArray *props = [NSArray arrayWithObjects:#"accessToken",nil];//[NSArray arrayWithObjects:#"accessToken", #"refreshToken",#"code", #"assertion", #"expirationDate", #"errorString",nil];
NSMutableString *valuesStr = [NSMutableString string];
NSString *separator = #"";
for (NSString *prop in props) {
id result = [self valueForKey:prop];
if (result)
{
[valuesStr appendFormat:#"%#",result];
separator = #", ";
}
}
return [NSString stringWithFormat:#"%#",valuesStr];
}
in .h file
#class GPPSignInButton;
#interface GPlusView : UIViewController <GPPSignInDelegate>
{
IBOutlet GPPSignInButton *signInButton;
}
#property (retain, nonatomic) IBOutlet GPPSignInButton *signInButton;
in .m file
signInButton_.shouldFetchGoogleUserEmail = TRUE;
signInButton_.delegate = self;
signInButton_.clientID = [SamacharAppDelegate clientID];
signInButton_.scope = [NSArray arrayWithObjects:
#"https://www.googleapis.com/auth/plus.me",
nil];
-(void)finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error
{
if (error) {
NSLog(#"Error = %#",error.localizedDescription);
return;
}
NSLog("Auth Data = %#",auth);
/* Auth Data = {accessToken="ya29.AHES6ZQYLmSBc9n4pLj9U8OQrFoTDZnGLH8okPkxbda7B0Q", refreshToken="1/puItTB-sqHupfp9qPCKcb6_gWUjgcxwzc9TKJvUwMEI", expirationDate="2012-11-24 13:30:55 +0000"} */
}

Related

How To get Sender E-mail from Device?

I am sending some data from my application to server. my data consist of different fields as my code shown below
-(void)createXML
{
xmlStr = #"<?xml version='1.0'?>\n<jand_req>\n<inquiryList>\n<productArr>\n";
NSString *nameStr=[NSString stringWithFormat:#"<name>%#</name>\n",name.text];
xmlStr=[xmlStr stringByAppendingString:nameStr];
NSString *compNameStr=[NSString stringWithFormat:#"<comp_name>%#</comp_name>\n",compName.text];
xmlStr=[xmlStr stringByAppendingString:compNameStr];
NSString *cityStr=[NSString stringWithFormat:#"<city>%#</city>\n",city.text];
xmlStr=[xmlStr stringByAppendingString:cityStr];
NSString *countryStr=[NSString stringWithFormat:#"<country>%#</country>\n",[nameToCode objectForKey:country.text]];
xmlStr=[xmlStr stringByAppendingString:countryStr];
NSString *commentsStr=[NSString stringWithFormat:#"<comment>%#</comment>\n",commentsBox.text];
xmlStr=[xmlStr stringByAppendingString:commentsStr];
xmlStr=[xmlStr stringByAppendingString:#"</userDetail>\n</inquiryList>\n</jand_req>"];
}
After this i send the above data to server as my code shown below
- (void)submitForm
{
[self createXML];
NSLog(#"myaccesscode%#",[fn getValFromSettings:#"accessCode"]);
NSString *serviceUrlStr=[NSString stringWithFormat:#"%#/%#/API_sendmail.php?access_code=%#",domainName,apiFolderPath,[fn getValFromSettings:#"accessCode"]];
NSLog(#"%#",serviceUrlStr);
NSURL * serviceUrl = [NSURL URLWithString:[serviceUrlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSMutableURLRequest * serviceRequest = [NSMutableURLRequest requestWithURL:serviceUrl cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:100];
[serviceRequest setValue:#"text/xml" forHTTPHeaderField:#"Content-type"];
[serviceRequest setHTTPMethod:#"POST"];
[serviceRequest setHTTPBody:[xmlStr dataUsingEncoding:NSUTF8StringEncoding]];
NSURLConnection *conn=[[[NSURLConnection alloc] initWithRequest:serviceRequest delegate:self startImmediately:YES] autorelease];
}
All the above code works fine for me but now i want to include an another feature in this code Which consist of sender E-mail address but this sender E-mail must be fetch from device same as when we use MFMailComposeViewController in application then automatically it gets sender E-mail Address from Device.Any help will be appriated thanks.
#import <AddressBook/AddressBook.h>
NSString *emailAddr = #"";
ABPerson *aPerson = [[ABAddressBook sharedAddressBook] me];
ABMultiValue *emails = [aPerson valueForProperty:kABEmailProperty];
if([emails count] > 0)
emailAddr = [emails valueAtIndex:0];
don't forget to add AddressBook.framework.
Now, the emailAddr contains the senders email which you can append to your xml string or wherever you want it to!
-(void)createXML
{
// Your code
NSString *emailStr=[NSString stringWithFormat:#"<email>%#</email>\n",emailAddr];
xmlStr=[xmlStr stringByAppendingString:emailStr];
}
happy coding!

NSMutableRequest and Flickr API for upload images

I use Flickr API for my app to manage user's photo. I decided to make authentication using Apple's classes and it works fine for me. Now my app is authenticated and has all necessary tokens and secret keys so it's possible to perform GET requests with authentication for methods like flickr.photos.search, flickr.test.login and so on.
But I spent a few days trying to perform upload using http://api.flickr.com/services/upload/
and their instructions here.
They say that request should have argument 'photo' and this parameter should not be included in the signature. That is clear, but I have no idea how to implement this parameter the request.
#import "FlickrUploader.h"
#import "HMACSH1.h"
#import "Prefs.h"
#import "NSString+URLEncode.h"
#implementation FlickrUploader
- (void)uploadPhotoAtPath:(NSString*)filePath {
NSString *upload_api_url = #"http://api.flickr.com/services/upload/";
NSString *oauth_nonce = [NSString stringWithFormat:#"%d", 10000000 + arc4random()%1000000];
NSString *oauth_timestamp = [NSString stringWithFormat:#"%d", (long)[[NSDate date] timeIntervalSince1970]];
NSString *oauth_consumer_key = CONSUMER_KEY;
NSString *oauth_signature_method = #"HMAC-SHA1";
NSString *oauth_version = #"1.0";
NSString *oauth_token = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_ACCESS_TOKEN_KEY];
//creating basestring to make signature without a 'photo' argument according to API
NSMutableString *basestring = [[NSMutableString alloc] initWithCapacity:8];
[basestring appendFormat:#"&oauth_consumer_key=%#",oauth_consumer_key];
[basestring appendFormat:#"&oauth_nonce=%#",oauth_nonce];
[basestring appendFormat:#"&oauth_signature_method=%#",oauth_signature_method];
[basestring appendFormat:#"&oauth_timestamp=%#",oauth_timestamp];
[basestring appendFormat:#"&oauth_token=%#", oauth_token];
[basestring appendFormat:#"&oauth_version=%#",oauth_version];
//this is may class to make HMAC-SHA1 signature (it works for authentication and for GET requests)
HMACSH1 *hMACSH1 = [[HMACSH1 alloc] init];
NSMutableString *urlEncodedBaseString = [[NSMutableString alloc] initWithCapacity:3];
[urlEncodedBaseString appendString:#"POST"];
[urlEncodedBaseString appendFormat:#"&%#",[upload_api_url urlEncodedString]];
[urlEncodedBaseString appendFormat:#"&%#",[basestring urlEncodedString]];
NSString *oauth_token_secret = [[NSUserDefaults standardUserDefaults] objectForKey:OAUTH_TOKEN_SECRET_KEY];
NSString *hash_key = [CONSUMER_SECRET stringByAppendingFormat:#"&%#",oauth_token_secret];
NSString *oauth_signature = [hMACSH1 hmacSH1base64ForData:urlEncodedBaseString keyValue:hash_key];
//creating url for request
NSMutableString *urlString = [[NSMutableString alloc] initWithCapacity:8];
[urlString appendFormat:#"%#",upload_api_url];
[urlString appendFormat:#"?"];
[urlString appendString:basestring];
[urlString appendFormat:#"&oauth_signature=%#", oauth_signature];
NSURL *authURL = [[NSURL alloc] initWithString:urlString];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:authURL
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:30.0];
request.HTTPMethod = #"POST";
UIImage *img = [UIImage imageNamed:filePath];
NSData *imgData = UIImageJPEGRepresentation(img, 0.8);
//here I don't know what to do :((( perhaps NSOutputStream
}

ios authentication with facebook and server side verification

My iOs app authenticates user with Facebook using facebook-sdk.
Now application connects to server and has to confirm that the user identity. Which is recommended way?
Probably iphone has to send some kind of token to server and server has to confirm it with facebook api call
do you have link to these docs?
hello u want to login with Facebook in your ios Application i have use this code for it pls check it
first take web view in you r Application and do connection with Nib file .and enter your facebook Appl
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *client_id = #"Enter your Application ";
NSString *redirect_uri = #"http://www.facebook.com/connect/login_success.html";
NSString *url_string = [NSString stringWithFormat:#"https://graph.facebook.com/oauth/authorize?client_id=%#&redirect_uri=%#&type=user_agent&display=touch", client_id, redirect_uri];
NSURL *url = [NSURL URLWithString:url_string];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
-(IBAction)getText:(id)sender{
NSLog(#"%#",[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"]);
}
- (void)webViewDidFinishLoad:(UIWebView *)_webView {
NSString *url_string = [((_webView.request).URL) absoluteString];
NSLog(#"%#",url_string);
NSRange access_token_range = [url_string rangeOfString:#"access_token="];
//coolio, we have a token, now let's parse it out....
if (access_token_range.length > 0) {
int from_index = access_token_range.location + access_token_range.length;
NSString *access_token = [url_string substringFromIndex:from_index];
NSLog(#"access_token: %#", access_token);
htmldata=[webView stringByEvaluatingJavaScriptFromString:#"document.documentElement.outerHTML"];
NSLog(#"%#",htmldata);
NSLog(#"%#",url_string);
NSArray *arr1=[htmldata componentsSeparatedByString:#"<title>"];
NSString *data=[arr1 objectAtIndex:1];
NSArray *arr2=[data componentsSeparatedByString:#"</title>"];
value=[[NSString alloc]initWithString:[arr2 objectAtIndex:0]];
NSLog(#"%#",value);
if([value isEqualToString:#"Success"])
{
MainScreenController *C = [[MainScreenController alloc]init];
[self.navigationController pushViewController:C animated:YES];
[C release];
}
}
}
thanks

How do I download a file from S3 to an iPhone application?

I am new to iPhone development. I am developing an iPhone application which needs to open files stored on Amazon's S3 service.
How do I download a file from S3 to my iPhone application? I have tried Amazon's SDK, but they don't seem to provide a means of downloading and saving a file. How do I go about obtaining a file's URL from S3 and saving it in my application?
I always use the ASIHttpRequest library to do this and it's quite simple, here's a sample code from their website:
NSString *secretAccessKey = #"my-secret-access-key";
NSString *accessKey = #"my-access-key";
NSString *bucket = #"my-bucket";
NSString *path = #"path/to/the/object";
ASIS3ObjectRequest *request = [ASIS3ObjectRequest requestWithBucket:bucket key:path];
[request setSecretAccessKey:secretAccessKey];
[request setAccessKey:accessKey];
[request startSynchronous];
if (![request error]) {
NSData *data = [request responseData];
} else {
NSLog(#"%#",[[request error] localizedDescription]);
}
You can't get easier than this :)
If you don't have the luxury of simplicity using ASI, and/or are stuck with AWSiOS SDK, it's not a lot different:
/* borrowed from MaurĂ­cio Linhares's answer */
NSString *secretAccessKey = #"my-secret-access-key";
NSString *accessKey = #"my-access-key";
NSString *bucket = #"my-bucket";
NSString *path = #"path/to/the/object";
/********************************************/
AmazonCredentials *credentials = [[AmazonCredentials alloc] initWithAccessKey: accessKey withSecretKey: secretAccessKey];
AmazonS3Client *connection = [[AmazonS3Client alloc] initWithCredentials: credentials];
S3GetObjectRequest *downloadRequest = [[[S3GetObjectRequest alloc] initWithKey:path withBucket: bucket] autorelease];
[downloadRequest setDelegate: self]; /* only needed for delegate (see below) */
S3GetObjectResponse *downloadResponse = [self.awsConnection getObject: downloadRequest];
Then you can look at downloadResponse.body and downloadResponse.httpStatusCode, preferable in a delegate:
-(void)request: (S3Request *)request didCompleteWithResponse: (S3Response *) response {
NSLog(#"Download finished (%d)",response.httpStatusCode);
/* do something with response.body and response.httpStatusCode */
/* if you have multiple requests, you can check request arg */
}

iphone SDK:How use URL to post data back?

I read a plist data at LightTableViewController.m
and I load a data like this :
LOG RESULT:
The Plist Data Is : (
{
category = 11;
id = 1;
name = "LIVING RM";
status = 0;
},
{
category = 11;
id = 2;
name = "BEDROOM RM";
status = 0;
}
)
I need to post the "id" and "status" back to the database
to control which light to turn on or turn off
And this part is the my post method,It's in LightCell0.m
- (void)switchToggled:(id)sender {
UISwitch *theSwitch = (UISwitch *)sender;
UITableViewCell *cell = (UITableViewCell *)theSwitch.superview.superview;
UITableView *tableView = (UITableView *)cell.superview;
NSIndexPath *indexPath = [tableView indexPathForCell:cell];
if(theSwitch.on) {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//This is my first post method,it is static,only get the indexPath,Not a real id and status I want to post back
NSString *post = [NSString stringWithFormat:#"lightcb%i=1", indexPath.row+1];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
else {
NSURL * url;
NSMutableURLRequest * request;
NSString *_urlString = #"http://10.85.28.99/req_light.php";
url = [self smartURLForString:_urlString];
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
//I got one error and one warring
//Error is "Request for member 'plist' in something not a structure or union"
//Warning is 'NSString' may not resopnd to '+stringWithFormat:value=ForKey'
NSString *post = [ NSString stringWithFormat:#"id=%i,status=0",
[[self.plist objectAtIndex:indexPath.row] valueForKey:#"id"]];
NSData *postData = [ NSData dataWithBytes: [ post UTF8String ] length: [ post length ] ];
[request setHTTPBody:postData];
self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}
}
So...my question is
<1>How to post two data back (is it right to use "," to separated two return variables ?
<2>How to eliminate the error "Request for member 'plist' in something not a structure or union"
Great Thanks
1) POST values are separated by '&' like GET values in an URL.
2) The 'Request for member'... line tells you that your member does not exist, or at least is not declared in this scope, the warning 'NSString may not respond...' tells you you're trying to invoke a message/method on NSString which should be invoked on another class (NSDictionary would be my guess here).