简体   繁体   English

如何使用SLRequest获取Twitter时间轴

[英]How to get the twitter timeline using SLRequest

I'm trying to add Twitter timeline to my iOS app. 我正在尝试将Twitter时间轴添加到我的iOS应用中。 Twitter gives the official sample code here: https://dev.twitter.com/docs/ios/making-api-requests-slrequest Twitter在此处提供了官方示例代码: https : //dev.twitter.com/docs/ios/making-api-requests-slrequest
My problem is: in line 70 我的问题是:在第70行

if (timelineData) {
    NSLog(@"Timeline Response: %@\n", timelineData);
}

The timeline data is successfully printed to the console. 时间轴数据已成功打印到控制台。 I tried to add 我试图添加

self.dict = timelineDate;

and

return self.dict;

at the end of the function, but actually it returns a empty dictionary. 在函数的末尾,但实际上它返回一个空字典。 I noticed that the process is done in another thread, so I tried 我注意到该过程是在另一个线程中完成的,所以我尝试了

dispatch_async(dispatch_get_main_queue(), ^{
    self.dict = timelineDate;
};

but it still not work. 但它仍然无法正常工作。 This may be very easy to solve, but I really can't find any resources from either Apple or Twitter. 这可能很容易解决,但是我真的找不到Apple或Twitter的任何资源。 Can anyone help? 有人可以帮忙吗?

I load tweets in my app using this function (compatible for twitter api v1.1 but needs twitter account to be synced in the device.) I am doing it using TWRequest you can do the same with SLRequest too. 我使用此功能(与twitter api v1.1兼容,但需要在设备中同步twitter帐户)在应用程序中加载tweets。我正在使用TWRequest进行此操作,您也可以使用SLRequest进行此操作。

//include twitter.framework 
#import <Twitter/Twitter.h>

+ (void)getTweetsFortwitterID:(NSString *)twitterID

{
    if(twitterID.length >0)
    {
    NSString * finalURL = [NSString stringWithFormat:@"https://api.twitter.com/1.1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=%@&count=10", twitterID];

    TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:finalURL] parameters:nil requestMethod:TWRequestMethodGET];

    ACAccountStore *accountStore = [[ACAccountStore alloc] init] ;

    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)
             {
                 NSArray *twitterAccounts = [accountStore accountsWithAccountType:accountType];

                 if([twitterAccounts count] >0
                    )
                 {
                 ACAccount *twitterAccount = [twitterAccounts objectAtIndex:0];
                 [postRequest setAccount:twitterAccount];

                 NSLog(@"request.account:%@",postRequest.account);

                 // Perform the request created above and create a handler block to handle the response.
                 NSMutableArray *tweetsArray=[[NSMutableArray alloc]init];

                 [postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {

                     // Parse the responseData, which we asked to be in JSON format for this request, into an NSDictionary using NSJSONSerialization.
                     NSArray *publicTimeline = nil;
                     NSError *jsonParsingError = nil;
                     if (responseData)
                     {
                         publicTimeline = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&jsonParsingError];
                         NSLog(@"publicTimeline : %@", publicTimeline);
                     }

                     if ([publicTimeline isKindOfClass:[NSArray class]])
                     {

                         for (int i =0; i<[publicTimeline count]; i++)
                         {
                             NSMutableDictionary *twitterDict=[[NSMutableDictionary alloc]init];

                             if ([[publicTimeline objectAtIndex:i] objectForKey:@"text"])
                             {
                                 NSLog(@"ID: %@", [[publicTimeline objectAtIndex:i] objectForKey:@"text"]);
                                 [twitterDict setObject:[[publicTimeline objectAtIndex:i] objectForKey:@"text"] forKey:@"text"];
                             }
                             if ([[publicTimeline objectAtIndex:i] objectForKey:@"created_at"])
                             {
                                 NSLog(@"ID: %@", [[publicTimeline objectAtIndex:i] objectForKey:@"created_at"]);
                                 [twitterDict setObject:[[publicTimeline objectAtIndex:i] objectForKey:@"created_at"]
                                                 forKey:@"created_at"];
                             }

                             if ([[publicTimeline objectAtIndex:i] objectForKey:@"user"])
                             {
                                 NSLog(@"ID: %@", [[publicTimeline objectAtIndex:i] objectForKey:@"created_at"]);
                                 [twitterDict setObject:[[[publicTimeline objectAtIndex:i] objectForKey:@"user"]objectForKey:@"profile_image_url"]
                                                 forKey:@"profile_image_url"];
                             }


                             [tweetsArray addObject:twitterDict];
                             NSLog(@"tweets:%@", tweetsArray);

                         }
                     }

                     if([tweetsArray count]>0)
                         [[NSNotificationCenter defaultCenter] postNotificationName:@"tweetsLoaded" object:tweetsArray];


                 }];
                 }

             }

         }];
    }


}

Hope it is useful. 希望它是有用的。

The problem is that the call to the api is asynchronous. 问题在于对api的调用是异步的。 That means that by the time you rerun the array, it isn't yet filled. 这意味着,当您重新运行数组时,它尚未填充。 The answer of satheeshwaran one way to work around this: you send a notification when the download has finished. 解决该问题的方法之一是satheeshwaran:下载完成后发送通知。 Another way would be to create a delegate method that is called after the download. 另一种方法是创建一个在下载后调用的委托方法。 This is a pattern that comes across quite frequently. 这是一个经常遇到的模式。

brainray provides one solution. Brainray提供了一种解决方案。 An easier one would be if you're loading the tweets inside of the TableViewController just call [self.tableView reloadData] after your dispatch_async call. 一个更简单的方法是,如果您要在TableViewController中加载推文,只需在dispatch_async调用之后调用[self.tableView reloadData]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM