2013-10-30 29 views
2

我需要使用Twitter API 1.1更新我的應用程序。 以前我檢索使用以下URL鳴叫:如何在沒有驗證的情況下通過hashtag檢索推文?

http://search.twitter.com/search.json?tag=ios&rpp=25

但現在這是行不通的。 我嘗試使用以下URL從Twitter的API文檔:

https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4 .

但它返回以下錯誤:

{"errors":[{"message":"Bad Authentication data","code":215}]} 

我怎樣才能找回這些鳴叫?

我想使用Twitter.framework,但任何建議將不勝感激。

+1

嘗試使用https://github.com/austinfitzpatrick/AFTweetFetcher – TonyMkenu

+0

這不正是我想要的。但這是一個很好的起點。非常感謝。 –

+0

我知道......)......祝你好運! – TonyMkenu

回答

6

我找到了解決方案。微博接受two types of authentication爲tweest檢索:

  1. 應用的用戶認證
  2. 僅應用認證 第一種類型的需要登錄,並通過與所述第二不需要,但它需要bearer token

起初我的請求看着下面的樣子:

NSURL *URL = [NSURL URLWithString:@"http://search.twitter.com/search.json?tag=ios&rpp=25"]; 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0]; 
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; 

現在看起來如下:

if(self.bearerToken == nil) return; 
NSURL *URL = [NSURL URLWithString:@"https://api.twitter.com/1.1/search/tweets.json?q=%%23ios&count=25"]; 
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:URL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:30.0]; 
[urlRequest setValue:[NSString stringWithFormat:@"Bearer %@", self.bearerToken] forHTTPHeaderField:@"Authorization"]; 
NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; 

而且這種方法需要增加兩個方法bearerToken_base64Encode

- (NSString *)bearerToken 
{ 
    if(_bearerToken == nil) 
    { 
     NSString * consumerKey = [config.consumerKey stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 
     NSString * consumerSecret = [config.consumerSecret stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]; 

     //the combined authentication key is "CONSUMER_KEY:CONSUMER_SECRET" run through base64 encoding. 
     //we'll use NSData instead of NSString here so that we can feed it directly to the HTTPRequest later. 
     NSString * combinedKey = [[self class] _base64Encode:[[NSString stringWithFormat:@"%@:%@", consumerKey, consumerSecret] dataUsingEncoding:NSUTF8StringEncoding]]; 

     NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.twitter.com/oauth2/token"]]; 
     [urlRequest setHTTPMethod:@"POST"]; 
     [urlRequest setValue:[NSString stringWithFormat:@"Basic %@", combinedKey] forHTTPHeaderField:@"Authorization"]; 
     [urlRequest setValue:[NSString stringWithFormat:@"application/x-www-form-urlencoded;charset=UTF-8"] forHTTPHeaderField:@"Content-Type"]; 
     [urlRequest setHTTPBody:[@"grant_type=client_credentials" dataUsingEncoding:NSUTF8StringEncoding]]; 
     NSData *data = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil]; 
     NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
     _bearerToken = [responseJSON valueForKey:@"access_token"]; 
    } 
    return _bearerToken; 
} 
+(NSString *)_base64Encode:(NSData *)data{ 
    //Point to start of the data and set buffer sizes 
    int inLength = [data length]; 
    int outLength = ((((inLength * 4)/3)/4)*4) + (((inLength * 4)/3)%4 ? 4 : 0); 
    const char *inputBuffer = [data bytes]; 
    char *outputBuffer = malloc(outLength); 
    outputBuffer[outLength] = 0; 

    //64 digit code 
    static char Encode[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz/"; 

    //start the count 
    int cycle = 0; 
    int inpos = 0; 
    int outpos = 0; 
    char temp; 

    //Pad the last to bytes, the outbuffer must always be a multiple of 4 
    outputBuffer[outLength-1] = '='; 
    outputBuffer[outLength-2] = '='; 

    /* http://en.wikipedia.org/wiki/Base64 
    Text content M   a   n 
    ASCII   77   97   110 
    8 Bit pattern 01001101 01100001 01101110 

    6 Bit pattern 010011 010110 000101 101110 
    Index   19  22  5  46 
    Base64-encoded T  W  F  u 
    */ 


    while (inpos < inLength){ 
     switch (cycle) { 
      case 0: 
       outputBuffer[outpos++] = Encode[(inputBuffer[inpos]&0xFC)>>2]; 
       cycle = 1; 
       break; 
      case 1: 
       temp = (inputBuffer[inpos++]&0x03)<<4; 
       outputBuffer[outpos] = Encode[temp]; 
       cycle = 2; 
       break; 
      case 2: 
       outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xF0)>> 4]; 
       temp = (inputBuffer[inpos++]&0x0F)<<2; 
       outputBuffer[outpos] = Encode[temp]; 
       cycle = 3; 
       break; 
      case 3: 
       outputBuffer[outpos++] = Encode[temp|(inputBuffer[inpos]&0xC0)>>6]; 
       cycle = 4; 
       break; 
      case 4: 
       outputBuffer[outpos++] = Encode[inputBuffer[inpos++]&0x3f]; 
       cycle = 0; 
       break; 
      default: 
       cycle = 0; 
       break; 
     } 
    } 
    NSString *pictemp = [NSString stringWithUTF8String:outputBuffer]; 
    free(outputBuffer); 
    return pictemp; 
} 

響應也發生了變化,所以我也必須更改解析器。 一版本:

NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithString:jsonStr]; 
if (responseDictionary) 
{ 
    id data = responseDictionary[@"results"]; 
    if ([data isKindOfClass:NSArray.class]) 
    { 
     NSArray *dataArray = (NSArray*)data; 
     for (NSDictionary *post in dataArray) 
     { 
       avatarUrl = post[@"profile_image_url"]; 
      author = post[@"from_user"]; 
      message = post[@"text"]; 

       NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
       [inputFormatter setDateFormat:@"EEE',' dd MMM yyyy HH:mm:ss ZZZZ"]; 
      date = [inputFormatter dateFromString: post[@"created_at"]]; 
     } 
    } 
} 

當前版本:

NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithString:jsonStr]; 
if (responseDictionary) 
{ 
    id data = [responseDictionary valueForKey:@"statuses"]; 
    if ([data isKindOfClass:NSArray.class]) 
    { 
     NSArray *dataArray = (NSArray*)data; 
     for (NSDictionary *post in dataArray) 
     {    
      avatarUrl = post[@"user"][@"profile_image_url"]; 
      author = post[@"user" ][@"name"];; 
      message = post[@"text"];   
        NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
        [inputFormatter setDateFormat:@"EEE MMM dd HH:mm:ss ZZZZ yyyy"]; 
       date = [inputFormatter dateFromString: post[@"created_at"]]; 
     } 
    } 
} 
+0

感謝分享+1 – TonyMkenu

+0

謝謝Dude!看起來像我甚至不需要使用該死的社交。框架!不知道是否有某個解決方案沒有授權的Twitter流api! – Morckovka

1

根據this doc不可能獲取Hashtag feed沒有Authentication

但是你可以在服務器端進行管理。在服務器端,您可以AuthenticateTwitter並從Twitter獲得Hash tag feed(此處還需要驗證以獲取訂閱源)。所以每當用戶不是AuthenticateiPhone那時你必須撥打Web Service而web服務將返回你在服務器端代碼管理的HashTag feed

而且,如果使用iOS設備(iPhone)上已經驗證的身份,則可以使用iOS獲取供稿。

相關問題