Flattr API v2 を使用して私の iOS アプリケーションから何かを flattr する私の実装の簡単な説明:
現在、「Mac 用 Google ツールボックス - OAuth 2 コントローラー」を使用しています:
http://code.google.com/p/gtm-oauth2/
認証するトークンを作成します。
- (GTMOAuth2Authentication *)flattrAuth {
NSURL *tokenURL = [NSURL URLWithString:@"https://flattr.com/oauth/token"];
// We'll make up an arbitrary redirectURI. The controller will watch for
// the server to redirect the web view to this URI, but this URI will not be
// loaded, so it need not be for any actual web page.
NSString *redirectURI = @"http://localhost/"; //for me localhost with / didn't work
GTMOAuth2Authentication *auth;
auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"MyApplication"
tokenURL:tokenURL
redirectURI:redirectURI
clientID:clientKey
clientSecret:clientSecret];
return auth;
}
トークンを認証する ViewController を作成します。
- (GTMOAuth2ViewControllerTouch*)getSignInViewController{
GTMOAuth2Authentication *auth = [self flattrAuth];
// Specify the appropriate scope string, if any, according to the service's API documentation
auth.scope = @"flattr";
NSURL *authURL = [NSURL URLWithString:@"https://flattr.com/oauth/authorize"];
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth
authorizationURL:authURL
keychainItemName:keychainItemName
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)] autorelease];
return viewController;
}
およびデリゲート メソッド:
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
if (error != nil) {
DLog(@"Flattr sign-in failed with error: %@", [error localizedDescription]);
} else {
DLog(@"Flattr Signin success");
authToken = [auth retain];
}
}
アプリケーションで Viewcontroller を表示できます。ユーザーは flattr-login を表示して、ユーザーがアプリケーションを認証できるようにします。
この方法で認証トークンを使用してフラット化できます。
NSString* flattrURL = @"https://api.flattr.com/rest/v2/things/%qi/flattr";
NSURL* u = [NSURL URLWithString:[NSString stringWithFormat:flattrURL, item.flattrThingID]];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:u];
[authToken authorizeRequest:request completionHandler:^(NSError *error){
if (error == nil) {
// the request has been authorized
NSURLConnection* connection = [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
if(!connection){
//TODO: handle error
} else {
[connection start];
}
} else {
//TODO: handle error
}
}];
次に、NSURLConnection デリゲート メソッドを実装し、JSON 応答を解析します。
GTMOAuth2 ライブラリを使用すると、認証済みトークンをキーチェーンに保存できます。手順については、 http://code.google.com/p/gtm-oauth2/wiki/Introduction#Retrifying_Authorization_from_the_Keychainの紹介をご覧ください。