iOS Geek

code and general geekiness.

Twitter Timeline Re-usable Class - iOS

I’m developing a Twitter tool and needed to grab the latest tweets in the public timeline and chuck (technical term) in a tableview for testing.

I’d also appreciate any comments if anyone spots any bad coding habits or would like to improve it.

Copy the code into your project making sure the calling class registers for the in its header file.

Then instantiate the class using your URL, I just use the standard Twitter Public Timeline Timeline API:

somewhere in your class
1
2
3
4
latestTweets *lt = [[latestTweets alloc] initWithTwitterURL:@"http://api.twitter.com/1/statuses/public_timeline.json?include_entities=true"];
lt.delegate = self;
[lt release];

Your calling class needs to implement the delegate call back method to capture the returned array:

1
2
3
4
- (void)returnedArray:(NSArray*)tArray;
{
//self.yourArray = tArray;
}

As it uses the JSON parser you’ll need to add that to your project as well:

https://github.com/stig/json-framework/

Hope you find it useful.

Nik

latestTweets header
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#import <Foundation/Foundation.h>
@protocol latestTweetsDelegate
- (void)returnedArray:(NSArray*)tArray;
@end
@interface latestTweets : NSObject {
NSMutableData *responseData;
NSMutableArray *resultsArray;
id<latestTweetsDelegate> delegate;
}
@property (nonatomic, retain) NSMutableArray *resultsArray;
@property (retain,nonatomic) id<latestTweetsDelegate> delegate;
- (id)initWithTwitterURL:(NSString *)twitterURL;
@end
latestTweets.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#import "latestTweets.h"
#import "SBJson.h"
@implementation latestTweets
@synthesize resultsArray, delegate;
- (id)initWithTwitterURL:(NSString *)twitterURL;
{
self = [super init];
if (self) {
responseData = [[NSMutableData data] retain];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:twitterURL]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
return self;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[connection release];
NSLog(@"Connection failed: %@", [error description]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
NSArray *newData = [responseString JSONValue];
[responseString release];
[self.delegate returnedArray:newData];
}
#pragma mark Memory Management
- (void)dealloc {
self.resultsArray = nil;
responseData = nil;
[respondeData release];
self.delegate = nil;
[super dealloc];
}
@end

Comments