Use RestKit with file-based URL - iphone

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.

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!

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.

oData Objective-C add a JSon stream

I try to add a Json strem form my odata server.
It work fine with jQuery, but in objective-c ther is only xml returned.
I try this :
DataModel *proxy = [[DataModel alloc] initWithUri:#"http://www.example.com/odata/odata.svc" credential:nil];
[proxy addHeader:#"Accept" headerValue:#"application/json, text/javascript, */*; sq=0.01"];
QueryOperationResponse *response = [proxy execute:#"Example"];
NSMutableArray *array = [response getResult];
It doesn't work.
How can I do?
thanks
Gwennin
xml is what odata will return. you will need to parse the results. Here is a link to a great tutorial for doing that.
http://www.raywenderlich.com/553/how-to-chose-the-best-xml-parser-for-your-iphone-project
If the returned type is a Collection<> of some sort, the OData library does the work for you and converts it to an array of the correct Entity in Objective-C.
If you return a simple type, parse the result. An example is using XPath queries (although for my service, I had to remove from the returned XML a couple of unsupported root element attributes that Odata returned).
If you chose to use Xpath,I love this code: http://cocoawithlove.com/2008/10/using-libxml2-for-parsing-and-xpath.html

how to do json parsing in iphone

i am using json parsing in my application
and this is my json data is as follow :
{"response" :
{"success":false,"error":
{"code":7,"description":"You are not logged in"}}}
and i want description means "You are not logged in" i my string
so how can i do that
please help me.....
Check the blog post with sample code and step by step parsing of JSON.
http://www.xprogress.com/post-44-how-to-parse-json-files-on-iphone-in-objective-c-into-nsarray-and-nsdictionary/
http://pessoal.org/blog/2008/12/12/iphone-sdk-parsing-json-data/
http://mobileorchard.com/tutorial-json-over-http-on-the-iphone/
We're using CJSONDeserializer (TouchJSON library) in the iPhone app being developed at work.
Just use the following method:
NSDictionary * dictionary = [[CJSONDeserializer deserializer] deserializeAsDictionary:data error:&error];
where data is of type NSData *. It will convert the JSON string into a dictionary so you could get the value of description as follows:
[[[dictionary objectForKey:#"response"] objectForKey:#"error"] objectForKey:#"description"];

Google Reader API with Objective-C - Problem getting token

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.