まゆたまガジェット開発逆引き辞典

電子工作やプログラミングのHowtoを逆引き形式で掲載しています。作りたいモノを決めて学んでいくスタイル。プログラマではないので、コードの汚さはお許しを。参照していないものに関しては、コピペ改変まったく問いません

Twitter検索してヒット数を表示(ただし取得したタイムライン内の数)

次はまたまた正規表現を使ってTwitterSearchAPIを使ったTwitter検索をして、ヒット数を出してみました。ただしこのヒット数はTwitter全体のヒット数ではなく、取得したタイムラインの中にいくつあったかというカウントです。
今回はRTされた数を出してみました。

サンプルは後日。とりあえず全体が以下です。
先にTextFieldを用意して、AccountsFrameworksとTwitterFrameworksを追加しておきます。

注意する点がひとつあって、UITextFiledに入力した文字を「http://search.twitter.com/search.json?q=%@&rpp=20」の%@に突っ込むために文字列として渡す処理は「- (void)loadTimeline」の中ではなく「- (IBAction)closeText:(id)sender {}」の中でやる必要があります。
UITextFiled(UIKit)の処理は外のスレッドでやったらアカンと怒られます。

・ViewController.h

#import <UIKit/UIKit.h>
#import <Accounts/Accounts.h>
#import <Twitter/Twitter.h>

@interface ViewController : UIViewController {
    NSMutableArray *tweetTextArray;
    ACAccount *account;
    ACAccountType *accountType;
    ACAccountStore *accountStore;
    NSString *str;
    NSString *searchString;
    
}
@property (weak, nonatomic) IBOutlet UITextField *SerchText;
- (IBAction)closeText:(id)sender;

- (void)loadTimeline;

@end

・ViewController.m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize SerchText;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
    accountStore = [[ACAccountStore alloc] init];
    accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
}

- (void)viewDidUnload
{
    [self setSerchText:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}

- (void)loadTimeline {
 
    tweetTextArray = [[NSMutableArray alloc] initWithCapacity:0];
    
    
    [accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error) {
        if (granted) {
            if (account == nil) {
                NSArray *accountArray = [accountStore accountsWithAccountType:accountType];
                account = [accountArray objectAtIndex:0];
            }
            if (account != nil) {
                //以下、URLを指定→そこにアクセスする設定をする→アクセスする
                //検索語を指定する。日本語を検索する場合は、UTF-8でURLエンコードした文字列を渡す
                //英語で入力しても大丈夫
                
                //UTF-8でURLエンコード
                NSString* encodStr = [searchString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
                //URLを指定
                NSString *urlString = [NSString stringWithFormat:@"http://search.twitter.com/search.json?q=%@&rpp=20",encodStr];
            
                
                //URLWithStringでNSURLのインスタンスを生成
                NSURL *url = [NSURL URLWithString:urlString];
                
            
                
                //NSURLRequestとurlStringで設定したアドレスにアクセスする設定をする
                NSURLRequest *request = [NSURLRequest requestWithURL:url];
                //NSURLConnectionで実際にアクセスする
                [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                    if (error) {
                        NSLog(@"error: %@", [error localizedDescription]);
                        return;
                    }
                    
                    //jsonで解析する
                    NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:nil];
                    //resultsにTweetが配列の形で入っている
                    NSArray *tweets = [dictionary objectForKey:@"results"];
                    
                    
                    //Tweetをひとつずつ取り出して表示する準備をする
                    for (NSDictionary *tweet in tweets) {
                        [tweetTextArray addObject:[tweet objectForKey:@"text"]];
                        str = [tweetTextArray componentsJoinedByString:@","];
                        
                        
                        
                        
           
                         }
                    
                    //ヒット数表示
                    NSRegularExpression *regexp =
                    [NSRegularExpression regularExpressionWithPattern:@"(RT)"
                                                              options:0 error:&error];
                    
                    NSMutableArray *resulta = [[NSMutableArray alloc] init];
                    
                    id proc = ^(NSTextCheckingResult *arre, NSMatchingFlags flag, BOOL *stop) {
                        [resulta addObject: [str substringWithRange:[arre rangeAtIndex:1]]];
                    };
                    
                    [regexp enumerateMatchesInString:str options:0
                                               range:NSMakeRange(0, str.length) usingBlock:proc];
                    int count = [resulta count];
                    
                  
                    //ヒット数表示
                    NSLog(@"%d",count);
                 
                 
                                        
                }];
            }
        }
    }];

    
}

- (IBAction)closeText:(id)sender {
    searchString = SerchText.text;
    [self loadTimeline];
          
}
@end