开发者

API Key and RESTKit

I'm using RESTKit for a service that was created for me. The model in JSON for my user is:

{
    "api_key" : "123456"
    "user" : {
        "username" : "user1",开发者_如何学运维
        "email"    : "me@email.com",
        "name"     : "name1",
        "surname"  : "surname1"
    }
}

I need introduce the api_key if I want to GET an user /users/1.json. I read in the documentation about set an app-wide API key HTTP header.

The example is:

[client setValue:@"123456" forHTTPHeaderField:@"X-RESTKIT-API-KEY"];

Is it the right way to do this? How can I discover my @"X-RESTKIT-API-KEY" of my service? (not api_key value, I search the string to replace @"X-RESTKIT-API-KEY" for my service)


Hmm, for that sample GET request, I suggest you to use RKClient object. I will give you some example:

#import <RestKit/RestKit.h>
#import "JSONKit.h"

RKClient* client = [RKClient clientWithBaseURL:@"http://yourdomainwhereisapi.com"]; 

and anywhere in you app (because RKCLient is singleton object) you can call:

// Here you need to define delegate in header (because delegate is self)
// Declare delegate in .h file with <RKRequestDelegate>
[[RKClient sharedClient] get:@"/some/api/call.json" delegate:self];

You must to define delegate method:

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response {
      // where you handle response object
      // sample how to make NSDictionary from JSON response
      NSDictionary *deserializedData = [[response bodyAsString] objectFromJSONString];

      // Now you can get anything from this NSDictionary:
      NSLog("%@", [deserializedData objectForKey:@"api_key"];
}

P.S. Anyway, you can take a look at RestKit wiki to see basic examples: RestKit Wiki tutorial

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜