2011年10月24日星期一

iOS 5 : Twitter Framework – Part 2

iOS 5 : Twitter Framework – Part 2:
In the previous post on iOS 5 and the new Twitter framework, I walked through how to use TWTweetComposeViewController to display a pre-built controller for easily integrating and posting to Twitter.

In this post I will show you how to use the TWRequest object to create an HTTP request, and in turn, sending and processing the results of the request. There are three primary components of a Twitter request: the URL of the desired Twitter service you are after, the type of HTTP request (GET, POST or DELETE) and any query parameters (required or optional) of the service requested. It’s also worth noting, using when using TWRequest user authentication is handled for you.



Twitter Search

By looking at the Twitter API I found how to properly setup a search request. Below I do a search for the string “iOS 5″, which looks like this when url-encoded: “q=iOS%205″. Check out the API for more information about the additional parameters.


#import <Twitter/Twitter.h>

...

// Do a simple search, using the Twitter API
TWRequest *request = [[TWRequest alloc] initWithURL:[NSURL URLWithString:
@"http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent"]
parameters:nil requestMethod:TWRequestMethodGET];

// Notice this is a block, it is the handler to process the response
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if ([urlResponse statusCode] == 200)
{
// The response from Twitter is in JSON format
// Move the response into a dictionary and print
NSError *error;       
NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&error];
NSLog(@"Twitter response: %@", dict);                          
}
else
NSLog(@"Twitter error, HTTP response: %i", [urlResponse statusCode]);
}];


And here is what a partial response, in JSON, looks like:


Twitter response: {
"completed_in" = "0.179";
"max_id" = 128283809723592705;
"max_id_str" = 128283809723592705;
"next_page" = "?page=2&max_id=128283809723592705&q=ios%205&rpp=5&with_twitter_user_id=1";
page = 1;
query = "ios+5";
"refresh_url" = "?since_id=128283809723592705&q=ios%205&with_twitter_user_id=1";
results =     (
{
"created_at" = "Mon, 24 Oct 2011 01:36:58 +0000";
"from_user" = XXXXXXXXXXX;
"from_user_id" = 14379847;
"from_user_id_str" = 14379847;
geo = "<null>";
id = 128283809723592705;
"id_str" = 128283809723592705;
"iso_language_code" = en;
metadata =             {
"result_type" = recent;
};
...
}


You can use the above query even if there is no Twitter account setup on the device – for example, copy/paste the URL http://search.twitter.com/search.json?q=iOS%205&rpp=5&with_twitter_user_id=true&result_type=recent into a browser to view the search request.

Twitter Post

Let’s look at how to create a custom tweet, that is, post to Twitter without using TWTweetComposeViewController.


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
#import <Accounts/Accounts.h>
#import <Twitter/Twitter.h>

...

if ([TWTweetComposeViewController canSendTweet])
{
// Create account store, followed by a twitter account identifier
// At this point, twitter is the only account type available
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];

// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];

// Sanity check
if ([arrayOfAccounts count] > 0)
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];

// Build a twitter request
TWRequest *postRequest = [[TWRequest alloc] initWithURL:
[NSURL URLWithString:@"http://api.twitter.com/1/statuses/update.json"]
parameters:[NSDictionary dictionaryWithObject:@"Custom tweet from iOS 5 Twitter framework. Visit iOSDeveloperTips.com for more information."
forKey:@"status"] requestMethod:TWRequestMethodPOST];

// Post the request
[postRequest setAccount:acct];

// Block handler to manage the response
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
NSLog(@"Twitter response, HTTP response: %i", [urlResponse statusCode]);
}];
}
}
}];
}


On line 14, the request for access will show a dialog as follows:



If all is well, we create an array of the available accounts, and using the first entry, create a TWRequest to post a tweet. Check out the Twitter API for specifics on the parameters.

Once the tweet has been posted, there is block handler to print the response to the console. A successful tweet should print: Twitter response, HTTP response: 200.

The successful Twitter post looks will look like this:



One last note, don’t forget to add the Twitter and Accounts frameworks to your project before compiling.

没有评论:

发表评论