Google Reader API with Objective-C - Problem getting token - iphone

I am able to successfully get the SID (SessionID) for my Google Reader account. In order to obtain the feed and do other operations inside Google Reader, you have to obtain an authorization token. I'm having trouble doing this. Can someone shed some light?
//Create a cookie to append to the GET request
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"SID",#"NSHTTPCookieName",self.sessionID,#"NSHTTPCookieValue",#".google.com",#"NSHTTPCookieDomain",#"/",#"NSHTTPCookiePath",nil];
NSHTTPCookie *authCookie = [NSHTTPCookie cookieWithProperties:cookieDictionary];
//The URL to obtain the Token from
NSURL *tokenURL = [NSURL URLWithString:#"http://www.google.com/reader/api/0/token"];
NSMutableURLRequest *tokenRequest = [NSMutableURLRequest requestWithURL:tokenURL];
//Not sure if this is right: add cookie to array, extract the headers from the cookie inside the array...?
[tokenRequest setAllHTTPHeaderFields:[NSHTTPCookie requestHeaderFieldsWithCookies:[NSArray arrayWithObjects:authCookie,nil]]];
//This gives me an Error 403 Forbidden in the didReceiveResponse of the delegate
[NSURLConnection connectionWithRequest:tokenRequest delegate:self];
I get a 403 Forbidden error as the response from Google. I'm probably not doing it right. I set the dictionary values according to the documentation for NSHTTPCookie.

The keys of a cookie properties should be the NSHTTPCookie constants, not literal strings as you give them.
NSDictionary *cookieDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"SID",NSHTTPCookieName,
self.sessionID,NSHTTPCookieValue,
#".google.com",NSHTTPCookieDomain,
#"/",NSHTTPCookiePath,
nil];
Note that the values constants aren't equal to their names; generally speaking, they appear to be the name without the "NSHTTPCookie" (e.g. NSHTTPCookieDomain == #"Domain"), but you shouldn't rely on this. Re-read the documentation.

Related

Using AFIncrementalStore with an Auth token

I'm working on an iOS client for App.net, and I'd like to use AFIncrementalStore to sync the web service with my Core Data implementation in the app.
I've gotten the two to work for API requests that don't require an auth token, but I can't figure out how to use the auth token with AFIncrementalStore.
In other words, I'm able to pull down the global feed, since it doesn't require auth:
https://alpha-api.app.net/stream/0/posts/stream/global
...however, to get a user's stream, you need auth (you'll note this link gives an error):
https://alpha-api.app.net/stream/0/posts/stream
I understand that I need to append an auth_token to the end of the API call, but I'm not sure how to do that using AFIncrementalStore.
Update: Here's the chunk of code that currently gets the global stream:
This is a method pulled directly from the example App.net project included in AFIncrementalStore.
-(NSURLRequest *)requestForFetchRequest:(NSFetchRequest *)fetchRequest withContext:(NSManagedObjectContext *)context {
NSMutableURLRequest *mutableURLRequest = nil;
if ([fetchRequest.entityName isEqualToString:#"Post"]) {
mutableURLRequest = [self requestWithMethod:#"GET" path:#"stream/0/posts/stream/global" parameters:nil];
}
return mutableURLRequest;
}
All you have to do with the case above to alter it to correctly use an access token is add parameters to the request instead of passing nil.
To build the parameters simply make an NSDictionary with the keys and values you need. For example in some of my App.net code I have this
NSDictionary *params = #{#"access_token": token};
Using the new compiler directives this builds an NSDictionary with a single key (in this case 'access_token') with the value in the NSString token.
After you have this just make your request something like:
[self requestWithMethod:#"GET" path:#"stream/0/posts/stream" parameters:params];
To pass the parameters in the request.
Let me know if this isn't clear enough!

Use RestKit with file-based URL

I want to use RestKit with a file-based URL:
file://localhost/Users/me/somefile.json
However, when I start a request with RestKit, RestKit can't create the corresponding RKURL object although the original is a valid NSURL object (completeURL is nil):
NSURL *completeURL = [NSURL URLWithString:completePathWithQuery relativeToURL:theBaseURL];
if (!completeURL) {
RKLogError(#"Failed to build RKURL by appending resourcePath and query parameters '%#' to baseURL '%#'", theResourcePath, theBaseURL);
[self release];
return nil;
}
Are file-based urls generally supported by RestKit?
Update: I posted an issue at RestKit
I'm just quoting the answer in the question owner's Update link so people may find it easier.
I found the problem I was having. It looks like I can't use #"file://localhost/Users/me/Folder" as baseURL, but rather #"file://localhost.
That is a NSURL method you are calling that is failing. Filing an issue with RestKit will not get that fixed.
From the documenation:
Return Value
An NSURL object initialized with URLString and baseURL. If URLString was malformed, returns nil.

RestKit - Appending a parameter to all requests

I have an iOS app using RestKit in order to communicate with a RESTful Rails server. The server uses a basic session token for authentication of users. I want to append this token to every request sent using the RKObjectManager's methods.
I've tried creating a Category overload of NSManagedObject in order to use the following method:
- (void)willSendWithObjectLoader:(RKObjectLoader *)objectLoader
That works fine, however I see no way of appending to the object loader's params. I've even gone as far as to reserialize the object but there is no way to do that without it being sent using escape characters. For example, the following code will give me the object in JSON serialized form
RKObjectMapping *serializationMapping = [[[RKObjectManager sharedManager] mappingProvider] serializationMappingForClass:[self class]];
RKObjectSerializer *ser = [RKObjectSerializer serializerWithObject:self mapping:serializationMapping];
NSObject<RKRequestSerializable> *obj = [ser serializationForMIMEType:RKMIMETypeJSON error:nil];
But the object returned there is intend to be used as a param right away so the following code does not work
[params setValue:[LCSingletonLoggedInUser sharedLoggedInUser].sessionToken forParam:#"token"];
[params setData:obj.HTTPBody forParam:#"data"];
I've also tried various combinations of setObject and setData and obj.HTTPBody as well as just obj right away.
Actually appending obj to params in any way will always result in it adding escape characters which the server can't handle. Setting params = obj will give the correct values to the server but won't include the token.
How about adding it to queryParams?
NSString *resourcePath = [#"/products" stringByAppendingQueryParameters:_queryParams];
Where queryParams is a NSMutableDictionary where you add your token.

Interprating API response from Google server

I am developing a Location based application. application will show route between to locations with turn by turn directions(as in native "Maps" application with all the nodes). I am requesting to google maps for directions in following way.(as example directions between cupertino and stanford)
NSString* apiUrlStr = [NSString stringWithFormat:#"http://maps.google.com/maps?dirflg=d&output=dragdir&saddr=Stanford&daddr=cupertino"];
NSURL* apiUrl = [NSURL URLWithString:apiUrlStr];
NSError* error = nil;
NSString* apiResponse = [NSString stringWithContentsOfURL:apiUrl encoding:NSASCIIStringEncoding error:&error];
NSLog(#"apiResponse=%#", apiResponse);
At the console I got response
{tooltipHtml:" (12.9\x26#160;mi / 19 mins)",polylines:[{id:"route0",points:"kklcFzishVdBb#??#s#rB{PHi#Xk#??bEmDrDgF~DeHVcAhCgG??rFfEv#RbFHnEa#vBGnEd#\\P~EjGtMxK??zNwTxB_ChCqD??bAt#bDdBvDt#~BXrC#xBS|NiClA#fAPvBdA~#dAlIQAxAr#n#|#d#rFxA|AlAAnAz#t#l##nAd#zQnC??bA\\^XVr#Az#KVa#\\m#B[UWq#?i#zBaI#oBd#mDt#kS~#kGAoDrA_DhAqB~AkBlCuBlDiB~Cw#lU}CbBa#~B{#jE_CvAgAjDyDhQ{SvFuFpUgSzD{EdAcBBiDlA_DfAaEbIk#r#mERyBZkMXkHX{DjA{GtBaG|CcFxC{CfAy#vUaMjDmEvA}BxCkGAwCfAyEtCiRv#{ClB_F|B_EpDkEvAoAdGcE|FwEbBmBvBmDhAiCtMma#dAcCrBmDLiNlB{CfAcCtEaMtKsUCmEdP{WbB_EbAoDr#}Dd#aFLkCC_FK_C{C}YMqGPsGRyC\eCdAeFpCaLdBiJXcENgHa#qIcIwo#[DWeFKk[Dyc#??\gHbAgI?#??|bAG???s#_#?",levels:"BBB???BB????BB?#???#??BB??BB???#????#????#??????#BB?????#???#????#???#??????#??????#???#????#?#?????#?????#??????#??#??#?????A???#????#??????#???#?BB??BBBB?B",numLevel`s:4,zoomFactor:16}]}
I am not able understand above response. Does this response contains turn by turn directions? If not how can get these directions?
According to Google Directions API documentation:
overview_polyline contains an object holding an array of encoded
points
That means you cannot directly read real points value.
Also:
Note: the Directions API may only be used in conjunction with
displaying results on a Google map; using Directions data without
displaying a map for which directions data was requested is
prohibited.

How to Separate HTML Response

I am using FConnect in my app. After the user logs in to his/her Facebook account I am getting his/her information as:
{
"id":"###########",
"name":"Vishnu Gupta",
"first_name":"Vishnu",
"last_name":"Gupta",
"link":"facebook a/c link id=#######",
"education":[{"school":{"id":"######","name":"st.joseph"},"type":"High School"}],
"gender":"male","email":"##########",
"timezone":5.5,
"locale":"en_US",
"verified":true,
"updated_time":"2010-11-27T10:10:25+0000"
}
I want to store user's information in database. To do that, I have to separate the user's information that is id, name, and email.
I tried using componentsSeparatedByString method but I do not understand how to retrieve the information in an array.
Can anyone help me????
The response you are getting is in JSON Format which basically have response in Array & Dictionary.
You will be getting this data in Dictionary..so you can access it by using the key value..
NSLog(#"%#",[NSDictionaryObject valueforkey:#"id"]);
NSLog(#"%#",[NSDictionaryObject valueforkey:#"name"]);
NSLog(#"%#",[NSDictionaryObject valueforkey:#"first_name"]);
Hope this will surely work for you.....
ya.....its corrrect.In detail:
Add JSON SDK then write the below code
SBJSON *json = [[SBJSON alloc] init];
NSDictionary *returnObject = [json objectWithString:InfoName];
NSString #id=[NSString stringWithFormat:#"%#",[returnObject objectForKey:#"id"]];
same for name ,email.
then Add these objects to Array and release the json
JSOn is good to use for "key-value' pair parsing.