次のコードを使用して、Twitter からトークンを取得して要求しようとしています。
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
int length = 42;
NSMutableString *nonce = [NSMutableString stringWithCapacity: length];
for (int i = 0; i < length; i++) {
[nonce appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
NSURL *requestTokenURL = [NSURL URLWithString:@"https://api.twitter.com/oauth/request_token"];
NSInteger numberOfSecs = round([[NSDate date]timeIntervalSince1970]);
NSString *timestampString = [NSString stringWithFormat:@"%i", numberOfSecs];
NSMutableDictionary *signingParams = [[NSMutableDictionary alloc]initWithCapacity:10];
[signingParams setObject:@"xxxxxxxxxxxxxxx" forKey:@"oauth_consumer_key"];
[signingParams setObject:[nonce copy] forKey:@"oauth_nonce"];
[signingParams setObject:@"HMAC-SHA1" forKey:@"oauth_signature_method"];
[signingParams setObject:timestampString forKey:@"oauth_timestamp"];
[signingParams setObject:@"1.0" forKey:@"oauth_version"];
NSMutableURLRequest *mURLRequest = [[NSMutableURLRequest alloc]initWithURL:requestTokenURL];
mURLRequest.HTTPMethod = @"POST";
NSString *callbackURLString = @"http://bytolution.com";
//that is one fat piece of code...
NSString *authenticationHeaderString = [NSString stringWithFormat:@"OAuth oauth_callback=\"%@\", oauth_nonce=\"%@\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"%@\", oauth_consumer_key=\"xxxxxxxxxxxxxxxxx\", oauth_signature=\"%@\", oauth_version=\"1.0\"", [callbackURLString URLEncodedString], nonce, timestampString, [BYOAuthSignatureString signatureStringWithParameters:signingParams URL:[mURLRequest.URL absoluteString] HTTPMethod:mURLRequest.HTTPMethod]];
[mURLRequest setValue:authenticationHeaderString forHTTPHeaderField:@"Authorization"];
NSHTTPURLResponse *urlResponse;
NSError *error;
NSData *responseData = [NSURLConnection sendSynchronousRequest:mURLRequest returningResponse:&urlResponse error:&error];
NSString *dataString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(@"data: %@, response:%@, error: %@", dataString , urlResponse.allHeaderFields, error);
クラスBYOAuthSignatureString
はリクエストに署名するための署名を作成し、リクエストのすべてのパラメーターをチェックしました。Twitter のドキュメントに従って動作するはずです。
しかし、私のログは言う
data: Failed to validate oauth signature and token, response:(null), error: Error Domain=NSURLErrorDomain Code=-1012 "The operation couldn’t be completed. (NSURLErrorDomain error -1012.)" UserInfo=0x20892200 {NSErrorFailingURLKey=https://api.twitter.com/oauth/request_token, NSErrorFailingURLStringKey=https://api.twitter.com/oauth/request_token, NSUnderlyingError=0x20891ac0 "The operation couldn’t be completed. (kCFErrorDomainCFNetwork error -1012.)"}
ご協力いただきありがとうございます!