I want to send a tweet directly from my iPhone app without showing TWTweetComposeViewController pop up
Also i want to get all followers
is there a way to do it from twitter framework on the ios5 or should i use another api!
If I have to use another api can u specify a great api for me ? because all the apis i found
on the internet was so old.
Thanks in advance
You can use TWRequest for programatically posting tweets from my app, if you are using iOS 5.0 and up. Posting tweets is quite straightforward and there is no need for an external framework or anything.
You need the #import <Twitter/Twitter.h>. You retrieve the twitter account from the iPhone account store (you could check if there are multiple accounts) and then you use the account to post the request.
Here is an example of a method for posting a tweet with an image.
- (void)shareTwitterImage:(UIImage *)image
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType withCompletionHandler:^(BOOL granted, NSError *error)
{
if(granted)
{
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0)
{
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
TWRequest *postRequest = [[TWRequest alloc] initWithURL:[NSURL URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"] parameters:[NSDictionary dictionaryWithObject:self.textViewOutlet.text forKey:#"status"] requestMethod:TWRequestMethodPOST];
[postRequest addMultiPartData:UIImagePNGRepresentation(image) withName:#"media" type:#"multipart/png"];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
//show status after done
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
NSLog(#"Twiter post status : %#", output);
}];
}
}
}];
}
There are quite a few options:
Well, on iOS 6, there is the Apple Social framework, and you can use SLComposeViewController to post to Twitter as well as Facebook and Sina Weibo, here are the docs. TWTweetComposeViewController has been deprecated, devices running iOS 6 will have to run into backward compatibility -- so avoid that.
There is also ShareKit, however I do not generally recommend it, its messy and bloated. Lastly there is the Oauth Library in iOS... create a consumer key and secret key. You can also call the Twitter API with TWRequest.
That's all of them I can think of.
Rohan.
In case you plan on integrating TwitterKit by Twitter to perform the tweets via your custom twitter app then this might help you.
https://stackoverflow.com/a/28602749/1740354
With the same methods you can get the followers list by using the following API
https://dev.twitter.com/rest/reference/get/followers/list
Hope it helps.
Related
I have integrated Facebook sharing using SLRequest into my iOS app. Everything works fine, but everytime I want to post, the user is shown a hint asking whether the app should be allowed to post on his behalf.
For some reasons (I'm posting from an Apple Watch), it would be important to get permanent permission to post. Otherwise it would be a very bad user experience.
So I'm looking after a possibility to permanently enable posting on the users behalf for my app.
- (void)postToFacebook:(NSString *)postMessage toAudience:(int)audienceIndex {
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeFacebook =
[accountStore accountTypeWithAccountTypeIdentifier:
ACAccountTypeIdentifierFacebook];
NSArray *audienceArray = [[NSArray alloc] initWithObjects:#"ACFacebookAudienceEveryone", #"ACFacebookAudienceFriends", #"ACFacebookAudienceOnlyMe", nil];
NSDictionary *options = #{ACFacebookAppIdKey: #"<HERE'S MY FACEBOOK APP ID>", ACFacebookPermissionsKey: #[#"publish_actions"], ACFacebookAudienceKey: [audienceArray objectAtIndex:audienceIndex]};
[accountStore requestAccessToAccountsWithType:accountTypeFacebook options:options completion:^(BOOL granted, NSError *error) {
if(granted) {
NSArray *accounts = [accountStore accountsWithAccountType:accountTypeFacebook];
ACAccount *facebookAccount = [accounts lastObject];
NSDictionary *parameters =
#{#"access_token":facebookAccount.credential.oauthToken,
#"message": postMessage};
NSURL *feedURL = [NSURL URLWithString:#"https://graph.facebook.com/me/feed"];
SLRequest *feedRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:feedURL parameters:parameters];
[feedRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSLog(#"Request failed, %#", [urlResponse description]);
}];
} else {
NSLog(#"Access Denied");
NSLog(#"[%#]",[error localizedDescription]);
}
}];
}
Unfortunately, there is no longer the notion of "permanent permission to post to Facebook".
The offline_access permission is deprecated and was removed December 5th, 2012 (originally scheduled for July 5th).
See: Developer Docs > Migration > Remove offline_access Permission
It was replaced by a new 60-day long term access token.
See: Developer Docs > Facebook Login > Access Tokens
Short-Term and Long-Term Tokens
User access tokens come in two forms: short-lived tokens and
long-lived tokens. Short-lived tokens usually have a lifetime of about
an hour or two, while long-lived tokens usually have a lifetime of
about 60 days. You should not depend on these lifetimes remaining the
same - the lifetime may change without warning or expire early. See
more under handling errors.
Access tokens generated via web login are short-lived tokens, but you
can upgrade them to long-lived tokens. Converting short-lived tokens
to long-lived tokens is covered later in this document under
Expiration and Extending Tokens.
Mobile apps that use Facebook's mobile SDKs get long-lived tokens.
Essentially, mobile applications using newer SDKs will automatically be granted a user access_token with the longer expiration. So long as a user revisits your app within 60 days, you will be granted a new user access_token with a fresh expiration time. If your users wait longer than 60 days, they will have to log in again.
i have used tweet sheet to tweet in my app,which works fine but can’t log out after setting ..i have to re launch the app to tweet
but what i want is to make a separate login button but in twitter is it possible to login and log out from twitter inside app?
Thanks loads in advance :)
I don't think that this is possible. You have to logout in your phones Settings.
You have to provide your own UI for Twitter login. E.g. once user entered twitter credentials you can first add Twitter account and then call Tweet sheet.
I doubt if log out or delete account is possible using SDK.
Sample code to add twitter account:
ACAccountStore *store = [[ACAccountStore alloc] init] ;
ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error) {
if(granted) {
ACAccount *twitterAccount = [[ACAccount alloc] initWithAccountType:[store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]];
ACAccountCredential *outhCredential = [[ACAccountCredential alloc] initWithOAuthToken:token.key tokenSecret:token.secret];
twitterAccount.credential = outhCredential;
[store saveAccount:twitterAccount withCompletionHandler:^(BOOL success, NSError *error) {
if(success)
{
[self performSelectorOnMainThread:#selector(showTweetSheet) withObject:nil waitUntilDone:NO];
}
}];
[outhCredential release];
[twitterAccount release];
[store release];
}
// Handle any error state here as you wish
}];
I'm trying to modify Apple's sample code for using the Twitter API so that I can use the streaming API to filter tweets. I am attempting to implement the method suggested in response to this question:
Does TWRequest work for the twitter streaming api?
I have created the signed NSURLRequest and NSURLConnection objects as suggested, and set the delegate for the connection object. A valid twitter account is selected and used to sign the url. The problem is that the delegates connection:didReceiveData: method is never being called.
Here's my code:
#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");
}
The output from the program is:
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
As you can see, everything appears to work OK, the only problem is that the delegate method is never called and I currently have no idea why.
Any help would be much appreciated...
Mike
It took me a bit of time to get this up and running, So I thought I aught to post my code for others. In my case I was trying to get tweets close to a certain location, so you will see that I used a locations parameter and a location struct I had in scope. You can add whatever params you want to the params dictionary.
Also note that this is bare bones, and you will want to do things such as notify the user that an account was not found and allow the user to select the twitter account they would like to use if multiple accounts exist.
Happy Streaming!
//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" forKey#"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)
}];
I am trying to make a basic iphone app that shows nearby tweets. I was using the TWRequest object to accomplish this with the twitter search api. Unfortunately, I would actually like to mark the tweets on a map using their GPS coordinates and the search api doesn't seem to return the actual location that a tweet was made with any better accuracy than the city name.
As such, I think I need to switch to the streaming api. I am wondering if it is possible to continue using the TWRequest object in this case or if I need to actually switch over to using NSURLConnection? Thanks in advance!
Avtar
Yes, you can use a TWRequest object. Create your TWRequest object using the appropriate URL and parameters from the Twitter API doco, and set the TWRequest.account property to the ACAccount object for the Twitter account.
You can then use the signedURLRequest method of TWRequest to get an NSURLRequest which can be used to create an asynchronous NSURLConnection using connectionWithRequest:delegate:.
Once this is done, the delegate's connection:didReceiveData: method will be called whenever data is received from Twitter. Note that each NSData object received may contain more than one JSON object. You will need to split these up (separated by "\r\n") before converting each one from JSON using NSJSONSerialization.
It took me a bit of time to get this up and running, So I thought I aught to post my code for others. In my case I was trying to get tweets close to a certain location, so you will see that I used a locations parameter and a location struct I had in scope. You can add whatever params you want to the params dictionary.
Also note that this is bare bones, and you will want to do things such as notify the user that an account was not found and allow the user to select the twitter account they would like to use if multiple accounts exist.
Happy Streaming!
//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" forKey#"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)
}];
I am working on an iOS app that I want to stream photos/pics in a users twitter account. For example, you can view a user's recent photos via https://twitter.com/#!/users_twitter_screenname/media/grid. I am wondering if there is such an api can work this out.
Basically, is there such an api can return the urls of these photos?
Thanks!
I figured out which twitter API to use to get the media url of a specified user. The API is the GET statuses/user_timeline API with the include_entities parameters set to true. The API will return 200 status of a user, if you want to get more result, you can use the page parameter to paginate through all twitter results.
Here are some sample codes using twitter API in iOS 5.
#include<Twitter/Twitter.h>
-(void)getUserTimeLine
{
TWRequest *postRequest = [[TWRequest alloc]
initWithURL:[NSURL URLWithString:#"http://api.twitter.com/1/statuses/user_timeline.json?screen_name=twitter&include_entities=true&trim_user=true&page=1"]
parameters:nil
requestMethod:TWRequestMethodGET];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if ([urlResponse statusCode]==200)
{
//Request succeed, then need to parse the json data returned.
//Do some parsing here.
}
else
{
//Request failed.
NSLog(#"HTTP response data:%i\n.",[urlResponse statusCode]);
}
}];
}