2012-07-23 2 views
2

Twitter API를 사용하여 Apple의 샘플 코드를 수정하여 스트리밍 API를 사용하여 트윗을 필터링 할 수 있습니다. 내가 제안 서명 NSURLRequest하고있는 NSURLConnection 개체를 만든Twitter iOS Streaming API : 데이터 수신하지 않음

Does TWRequest work for the twitter streaming api?

, 연결 객체의 대리자를 설정 :이 질문에 대한 응답 방법을 구현하는 것을 제안 시도하고있다. 유효한 트위터 계정이 선택되어 URL에 서명하는 데 사용됩니다. 문제는 delegates connection : didReceiveData : 메서드가 결코 호출되지 않는다는 것입니다.

@implementation Twitter 

-(id)init{ 
    if (self=[super init]) { 
     NSLog(@"Twitter init"); 

     // Tell the notification centre to inform the app if the twitter account changes 
     [[NSNotificationCenter defaultCenter] addObserver:self 
               selector:@selector(twitterAccountChanged) 
                name:ACAccountStoreDidChangeNotification object:nil]; 

     // Create an account store object. 
     ACAccountStore *accountStore = [[ACAccountStore alloc] init]; 

     // Create an account type that ensures Twitter accounts are retrieved. 
     ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 


     // Request access from the user to use their Twitter accounts. 
     [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) { 
      if(granted) { 
       NSLog(@"Twitter: Access to twitter accounts granted"); 

       // Get the list of Twitter accounts. 
       NSArray *accountsArray = [accountStore accountsWithAccountType:accountType]; 

       // Pick the twitter account to use 
       if ([accountsArray count] > 0) { 

        // Grab the initial Twitter account to tweet from. 
        ACAccount *twitterAccount = [accountsArray objectAtIndex:0]; 

        // This is for a status filter 
        NSURL *url=[NSURL URLWithString:@"https://stream.twitter.com/1/statuses/filter.json"]; 

        // Create the parameters dictionary 
        NSDictionary *dictionary=[NSDictionary dictionaryWithObjectsAndKeys:@"twitter", @"track", nil]; 

        // Create TWRequest object 
        TWRequest *req=[[TWRequest alloc] initWithURL:url parameters:dictionary requestMethod:TWRequestMethodPOST]; 

        // Set the account 
        [req setAccount:twitterAccount]; 

        // Get a signed URL request 
        NSURLRequest *signedRequest=[req signedURLRequest]; 

        // Initate the connection 
        [NSURLConnection connectionWithRequest:signedRequest delegate:self]; 

       } else { 
        NSLog(@"Twitter: No twitter accounts to access"); 
       } 

      } else { 
       NSLog(@"Twitter: Access to twitter accounts denied"); 

      } 
     }]; 

     return self; 
    } 
    return nil; 
} 

-(void)twitterAccountChanged{ 
    NSLog(@"Twitter twitterAccountChanged"); 
} 


-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ 
    NSLog(@"data received"); 
} 

프로그램의 출력은 다음과 같습니다 : 여기

내 코드의

2012-07-24 09:50:03.668 TwitterAPITest[36722:10403] Twitter init 
2012-07-24 09:50:03.836 TwitterAPITest[36722:11d03] Twitter: Access to twitter accounts granted 

당신이 볼 수 있듯이이 모든 것이 OK 작업 표시, 유일한 문제는 위임 방법은 결코 없다는 것입니다 불렀고 나는 현재 이유를 모른다.

어떤 도움이 많이 주시면 감사하겠습니다 ...

마이크

+0

글을 올린 후 TWRequest 객체를 ** 사용하지 않고이 작업을 ** 수행했습니다. 대신 NSURLRequest/Connection 객체를 사용하고, 스트리밍 API에서 JSON을 받고, 들어오는 트윗 텍스트를 파싱합니다. 비록 누군가가 TWRequest와 함께 작동하는 스트리밍 API를 얻었는지 알기에 여전히 좋을 것입니다 ... – Michael

+0

이 코드를 게시 할 수 있습니까? 감사. – EvilPenguin

+0

문제는 간단히 NSURLConnection이 주 실행 루프에서 시작 되었기 때문에 스레드가 호출되어 대리자를 호출 할 수 없기 때문입니다. 아래에 몇 가지 코드를 게시했습니다. – wbarksdale

답변

1

그것은이를 설치하고 실행하는 나에게 약간의 시간을했다, 그래서 나는 어떤 일이 다른 사람에 대한 내 코드를 게시 생각. 제 경우에는 특정 위치에 트윗을 가까이하려고했기 때문에 locations 매개 변수와 위치 범위 구조체를 사용했음을 알 수 있습니다. 원하는 매개 변수를 매개 변수 사전에 추가 할 수 있습니다.

또한이 계정은 기본 계정이 아니므로 계정을 찾을 수 없다는 사실을 사용자에게 알리는 등의 작업을 수행하고 여러 계정이있는 경우 사용할 트위터 계정을 선택할 수 있습니다.

해피 스트리밍 중!

//First, we need to obtain the account instance for the user's Twitter account 
ACAccountStore *store = [[ACAccountStore alloc] init]; 
ACAccountType *twitterAccountType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; 

// Request permission from the user to access the available Twitter accounts 
[store requestAccessToAccountsWithType:twitterAccountType 
       withCompletionHandler:^(BOOL granted, NSError *error) { 
        if (!granted) { 
         // The user rejected your request 
         NSLog(@"User rejected access to the account."); 
        } 
        else { 
         // Grab the available accounts 
         NSArray *twitterAccounts = [store accountsWithAccountType:twitterAccountType]; 
         if ([twitterAccounts count] > 0) { 
          // Use the first account for simplicity 
          ACAccount *account = [twitterAccounts objectAtIndex:0]; 
          NSMutableDictionary *params = [[NSMutableDictionary alloc] init]; 
          [params setObject:@"1" forKey:@"include_entities"]; 
          [params setObject:location forKey:@"locations"]; 
          [params setObject:@"true" forKey:@"stall_warnings"]; 
          //set any other criteria to track 
          //params setObject:@"words, to, track" [email protected]"track"]; 

          // The endpoint that we wish to call 
          NSURL *url = [NSURL URLWithString:@"https://stream.twitter.com/1.1/statuses/filter.json"]; 

          // Build the request with our parameter 
          TWRequest *request = [[TWRequest alloc] initWithURL:url 
                     parameters:params 
                    requestMethod:TWRequestMethodPOST]; 

          // Attach the account object to this request 
          [request setAccount:account]; 
          NSURLRequest *signedReq = request.signedURLRequest; 

          // make the connection, ensuring that it is made on the main runloop 
          self.twitterConnection = [[NSURLConnection alloc] initWithRequest:signedReq delegate:self startImmediately: NO]; 
          [self.twitterConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                forMode:NSDefaultRunLoopMode]; 
          [self.twitterConnection start]; 

         } // if ([twitterAccounts count] > 0) 
        } // if (granted) 
       }]; 
+0

당신은 내 하루를 저장했습니다 :) +1 –

+0

@wbarksdale 인증이 필요함에 따라 resposne을 받고 있습니다. 이것에 관해서 아이디어가 있습니까? 우리는 ACAccount를 사용하여 액세스 권한을 부여하므로 작동해야합니다. 어떤 도움을 주시면 감사하겠습니다. 감사. –

관련 문제