经过两天的挫折和诅咒推特,我终于设法做到了。这是我的实现。用于发出请求的类是“BL_TwitterRequest”。这仅用于获取 twitter 请求令牌。
BL_TwitterRequest.h:
#import <Foundation/Foundation.h>
@interface BL_Request : NSObject <NSURLConnectionDelegate>
@property (nonatomic, strong) NSMutableData *webData;
-(void) makeRequest;
在实现类 (BL_TwitterRequest.m) 的顶部添加以下 NSString 类别。这将用于获取 NSString 的 URL 编码版本。
@implementation NSString (NSString_Extended)
- (NSString *)urlencode {
NSMutableString *output = [NSMutableString string];
const unsigned char *source = (const unsigned char *)[self UTF8String];
int sourceLen = strlen((const char *)source);
for (int i = 0; i < sourceLen; ++i) {
const unsigned char thisChar = source[i];
if (thisChar == ' '){
[output appendString:@"+"];
} else if (thisChar == '.' || thisChar == '-' || thisChar == '_' || thisChar == '~' ||
(thisChar >= 'a' && thisChar <= 'z') ||
(thisChar >= 'A' && thisChar <= 'Z') ||
(thisChar >= '0' && thisChar <= '9')) {
[output appendFormat:@"%c", thisChar];
} else {
[output appendFormat:@"%%%02X", thisChar];
}
}
return output;
}
@end
在“BL_TwitterRequest.m”中添加以下函数。它将用于生成 oAuth 随机数。该函数基本上生成一个指定长度的随机字符串。
-(NSString*) generateRandomStringOfLength:(int)length {
NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
NSMutableString *randomString = [NSMutableString stringWithCapacity: length];
for (int i = 0; i < length; i++) {
[randomString appendFormat: @"%C", [letters characterAtIndex: arc4random() % [letters length]]];
}
return randomString;
}
从此处包含 Base64 库。您所要做的就是将“Base64.h”和“Base64.m”文件拖到您的项目中。添加以下导入:
#include <CommonCrypto/CommonDigest.h>
#include <CommonCrypto/CommonHMAC.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#import "Base64.h"
添加另一个函数,如下所示。这将用于获取 HMAC-SHA1 值。
- (NSString *)hmacsha1:(NSString *)data secret:(NSString *)key {
const char *cKey = [key cStringUsingEncoding:NSASCIIStringEncoding];
const char *cData = [data cStringUsingEncoding:NSASCIIStringEncoding];
unsigned char cHMAC[CC_SHA1_DIGEST_LENGTH];
CCHmac(kCCHmacAlgSHA1, cKey, strlen(cKey), cData, strlen(cData), cHMAC);
NSData *HMAC = [[NSData alloc] initWithBytes:cHMAC length:sizeof(cHMAC)];
NSString *hash = [HMAC base64EncodedString];
return hash;
}
现在是发出请求的主要功能。
-(void) makeRequest {
_webData = [[NSMutableData alloc]init]; // WILL BE USED BY NSURLConnection
NSString *httpMethod = @"POST";
NSString *baseURL = @"https://api.twitter.com/oauth/request_token";
NSString *oauthConsumerKey = @"YOUR_CONSUMER_KEY";
NSString *oauthConsumerSecret = @"YOUR_CONSUMER_SECRET";
NSString *oauth_timestamp = [NSString stringWithFormat:@"%.f", [[NSDate date]timeIntervalSince1970]];
NSString *oauthNonce = [self generateRandomStringOfLength:42];
NSString *oauthSignatureMethod = @"HMAC-SHA1";
NSString *oauthVersion = @"1.0";
NSString *oauthCallback = @"YOUR_TWITTER_CALLBACK_URL";
//1. PERCENT CODE EVERY KEY AND VALUE THAT WILL BE SIGNED AND
// APPEND KEY AND VALUE WITH = AND &
NSMutableString *parameterString = [[NSMutableString alloc]initWithFormat:@""];
[parameterString appendFormat:@"oauth_callback=%@", [oauthCallback urlencode]];
[parameterString appendFormat:@"&oauth_consumer_key=%@", [oauthConsumerKey urlencode]];
[parameterString appendFormat:@"&oauth_nonce=%@", [oauthNonce urlencode]];
[parameterString appendFormat:@"&oauth_signature_method=%@", [oauthSignatureMethod urlencode]];
[parameterString appendFormat:@"&oauth_timestamp=%@", [oauth_timestamp urlencode]];
[parameterString appendFormat:@"&oauth_version=%@", [oauthVersion urlencode]];
//2. CREATE SIGNATURE STRING WITH HTTP METHOD AND ENCODED BASE URL AND PARAMETER STRING
NSString *signatureBaseString = [NSString stringWithFormat:@"%@&%@&%@", httpMethod, [baseURL urlencode], [parameterString urlencode]];
//3. GET THE SIGNING KEY NOW FROM CONSUMER SECRET
NSString *signingKey = [NSString stringWithFormat:@"%@&", [oauthConsumerSecret urlencode]];
//4. GET THE OUTPUT OF THE HMAC ALOGRITHM
NSString *oauthSignature = [self hmacsha1:signatureBaseString secret:signingKey];
// TIME TO MAKE THE CALL NOW
NSMutableString *urlString = [[NSMutableString alloc]initWithFormat:@""];
[urlString appendFormat:@"%@", baseURL];
// INITIALIZE AUTHORIZATION HEADER
NSMutableString *authHeader = [[NSMutableString alloc]initWithFormat:@""];
[authHeader appendFormat:@"OAuth "]; // MIND THE SPACE AFTER 'OAuth'
[authHeader appendFormat:@"oauth_nonce=\"%@\",", [oauthNonce urlencode]];
[authHeader appendFormat:@"oauth_callback=\"%@\",", [oauthCallback urlencode]];
[authHeader appendFormat:@"oauth_signature_method=\"%@\",", [oauthSignatureMethod urlencode]];
[authHeader appendFormat:@"oauth_timestamp=\"%@\",", [oauth_timestamp urlencode]];
[authHeader appendFormat:@"oauth_consumer_key=\"%@\",", [oauthConsumerKey urlencode]];
[authHeader appendFormat:@"oauth_signature=\"%@\",", [oauthSignature urlencode]];
[authHeader appendFormat:@"oauth_version=\"%@\"", [oauthVersion urlencode]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:[NSURL URLWithString:urlString]] ;
[request setHTTPMethod:httpMethod];
[request setValue:authHeader forHTTPHeaderField:@"Authorization"];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[connection start];
}
现在只需实现 NSURLConnection 委托方法来获取响应。
#pragma mark - Connection Delegate
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[_webData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *resultString = [[NSString alloc]initWithData:_webData encoding:NSUTF8StringEncoding];
NSLog(@"RESULT STRING : %@", resultString);
}
如果一切顺利,'resultString' 将具有 oauth_token 和 oauth_token_secret。
要拨打电话,只需执行以下操作:
BL_TwitterRequest *twitterRequest = [[BL_TwitterRequest alloc]init];
[twitterRequest makeRequest];
请记住,任何遗漏的空格或逗号都可能导致错误。