As a part of my project I need to show the list of tweets in iOS app. I tried with the below code but its returning the JSON. The same code is works fine with version 1. Now the twitter api version is 1.1 and one another warning I got that TWRequest is deprecated. This deprecation is not the issue of this even I got same thing with SLRequest. Here my problem is I need to fetch the JSON of Particular user tweets without authentication or with authentication
TWRequest *postequest=[[TWRequest alloc]initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.0/statuses/user_timeline.json?screen_name=coolCracker&count=2"] parameters:nil requestMethod:TWRequestMethodGET];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output;
if ([urlResponse statusCode]==200) {
NSError *err;
NSDictionary *PublicTimeline=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];
output=[NSString stringWithFormat:#"HTTP response status: %li\nPublic timeline:\n%#",(long)[urlResponse statusCode],PublicTimeline];
}
else
{
output=[NSString stringWithFormat:#"No feed HTTP response was: %li\n",(long)[urlResponse statusCode]];
}
[self performSelectorOnMainThread:#selector(displayResults:) withObject:output waitUntilDone:NO];
}];
-(void)displayResults:(NSString *)text
{
NSLog(#"tweets feed %#",text);
}
I used this in my work and it worked pretty well. Use STTwitter. Download STTwitter files here.
Place this in your view didload:
STTwitterAPI *twitter = [STTwitterAPI twitterAPIAppOnlyWithConsumerKey:#"your consumer key"
consumerSecret:#"your secret key"];
[twitter verifyCredentialsWithSuccessBlock:^(NSString *bearerToken) {
[twitter getUserTimelineWithScreenName:#"your twitter account name"
successBlock:^(NSArray *statuses) {
self.twitterFeedList = [NSMutableArray arrayWithArray:statuses];
[self->listView reloadData];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];
} errorBlock:^(NSError *error) {
NSLog(#"%#", error.debugDescription);
}];
Hi Below code is working for me. Though TWRequest is deprecated it works for now. Later you can change it to SLRequest.
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
// Request access from the user to use their Twitter accounts.
[accountStore requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error) {
if (granted == YES){
//get accounts to use.
NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
if ([accounts count] > 0) {
NSLog(#"account: %#", accounts);
ACAccount *loggedinaccount;
loggedinaccount = accounts[0];
// get tweets
TWRequest *postRequest=[[TWRequest alloc]initWithURL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=HuntEthane&count=2"] parameters:nil requestMethod:TWRequestMethodGET];
[postRequest setAccount:loggedinaccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output;
if ([urlResponse statusCode]==200) {
NSError *err;
NSDictionary *PublicTimeline=[NSJSONSerialization JSONObjectWithData:responseData options:0 error:&err];
output=[NSString stringWithFormat:#"HTTP response status: %li\nPublic timeline:\n%#",(long)[urlResponse statusCode],PublicTimeline];
}
else
{
output=[NSString stringWithFormat:#"No feed HTTP response was: %li\n",(long)[urlResponse statusCode]];
}
[self performSelectorOnMainThread:#selector(displayResults:) withObject:output waitUntilDone:NO];
}];
}
}else{
// show alert to inser user_name and password to login on twitter
UIAlertView *alertTwitterAccount = [[UIAlertView alloc]
initWithTitle:#"Enter with your twitter account"
message:nil
delegate:self
cancelButtonTitle:#"Cancel"
otherButtonTitles:#"Login", nil];
[alertTwitterAccount setAlertViewStyle:UIAlertViewStyleLoginAndPasswordInput];
[[alertTwitterAccount textFieldAtIndex:0] setPlaceholder:#"User"];
[alertTwitterAccount setDelegate:self];
[alertTwitterAccount setTag:1];
[alertTwitterAccount show];
}
}];
Remember to add below frameworks to make this code work.
Twitter.FrameWork
Social.FrameWork
Accounts.Framework
Security.FrameWork
If you want to use SLRequest instead of TWRequest, replace request statement with below statement
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:[NSURL URLWithString:#"https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=HuntEthane&count=2"]parameters:nil];
Moving forward the easiest way is adoption of Fabric.io from Tweeter as the development platform includes Tweeter embeds: https://get.fabric.io/native-social
"The easiest way to bring Twitter content into your app."
Honestly, I did not look into authentication part needed for Fabric.io.
Otherwise you need to follow and respect rules for accessing Twitter REST APIs or Streaming APIs, both well documented. OAuth authentication is required.
If you wish to avoid authentication in your app you can write a simple web REST API that will take care of authentication and serve (selected) tweets to your iOS app.
First, you’ll need to register an app with Twitter
Write down your Consumer Key and Consumer Secret
Write a simple server API (proxy) in your language of choice.
I personally prefer JavaScript on Node.js. Consider using libraries like express.js and oauth available on npm, but you can search npm for any other implemented Twitter proxy/API.
The code essentially consists of getting an OAuth Access token and then calling selected twitter APIs, and respecting ratelimits by caching results.
Related
How can i send the URL to twitter friend in iOS.
I can send direct message but it does not allow me to send URL in it.
Here is my code for Posting Drirect message to Twitter Friend and its working.
-(void)postMessageToFriend:(NSString *)ID withMessage:(NSString *)message {
NotificatioName = notificationNameStr;
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted && !error) {
NSArray *accountsListAry = [accountStore accountsWithAccountType:accountType];
int NoOfAccounts = [accountsListAry count];
if (NoOfAccounts >0) {
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/direct_messages/new.json"];
twitterAccount = [accountsListAry lastObject];
NSDictionary *p =#{#"status":#"Posted",#"screen_name":ID, #"text":message};
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodPOST URL:url parameters:p];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResposnse, NSError *error){
if (error) {
NSLog(#"error : %#",error);
}else{
NSError *jsonError = nil;
NSString * responseStr = [[NSString alloc] initWithData:responseData encoding:NSJSONWritingPrettyPrinted];
NSArray *friendsdata =
[NSJSONSerialization JSONObjectWithData: [responseStr dataUsingEncoding:NSUTF8StringEncoding]
options: NSJSONReadingMutableContainers
error: &jsonError];
NSLog(#"response value is: %# %d ",friendsdata,[urlResposnse statusCode]);
}
}];
}
}
}];
}
But If i try to add URL in my message than its return me this error
{
errors = (
{
code = 226;
message = "This request looks like it might be automated. To protect our users from spam and other malicious activity, we can't complete this action right now. Please try again later.";
}
);
}
I think it has nothing to do with your code, but with Twitter. Apparently, they're not allowing to send links in direct messages. https://support.twitter.com/articles/14606-posting-or-deleting-direct-messages.
You can't do that even as a user from the official twitter client or from their website. AFAIK, it's a known issue and they're said to be working on it. But it's been long since they said that.
Your request is refused by Twitter because it is signed with OS X consumer tokens, as all instances of SLRequest are.
If you want to send URLs in direct messages, you have to sign your requests with the consumer tokens from an official Twitter client.
This cannot be done with SLRequest but can be done with third-party libraries such as STTwitter.
It is not a proper answer but stil i am sharing it. In my case I have to share the link of my app in the direct message. Message with url in the message text doesn't work but link of any twitter account can be shared with the message text. So I made a twitter acc for my app and give the link there.
I am trying to integrate Twitter in my iOS application.
The application is expected to support iOS versions 6.x & 7.x.
I want to directly post a tweet once the user taps on a button in my UI, without again asking confirmation in SLComposeViewController alert.
I have gone through the following posts which say how to do that, problem being that they are both configured for iOS 5.x.
Stack Overflow Link 1
Stack Overflow Link 2
How exactly do I go about it?
Any help will be appreciated.
I see no differences from iOS 5.1 to iOS 6.0, neither iOS 6.1 to 7.0 for Twitter api.
Use the iOS 5 tutorials and check with alt+left mouse click to inform about deprications or modified functions if there are.
Maybe this will help.
In the two links you mentioned they are using Twitter Api v1. which is deprecated a long time ago: API V1 no longer function instead you should be using the V1.1 so the url to post a tweet will be https://api.twitter.com/1.1/statuses/update.json
In addition TWRequest is also deprecated in iOS 6.0 you should use SLRequest
Here is a simple code to do so:
- (void) sendTweetWithoutPromp:(NSString*) tweetText
{
NSString *url = #"https://api.twitter.com/1.1/statuses/update.json";
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:tweetText forKey:#"status"];
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if(granted)
{
NSArray *accountsArray = [accountStore accountsWithAccountType:accountType];
if ([accountsArray count] > 0)
{
ACAccount *twitterAccount = [accountsArray objectAtIndex:0];
SLRequest *postRequest = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:TWRequestMethodPOST URL:[NSURL URLWithString:url] parameters:params ];
[postRequest setAccount:twitterAccount];
[postRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
NSLog(#"output = %#",output);
dispatch_async( dispatch_get_main_queue(), ^{
if (error)
{
}
});
}];
}
else
{
NSLog(#"no Account in Settings");
}
}
}];
}
I'm new to iOS development so I'm not clear about how to go about this: with the username and password provided by the user, check if the credentials is a valid twitter account. Log the user in and retrieve the users followers, account information, timeline and tweets.
I know I haven't tried anything, but it's just because I have no clue where to start. I did some searching up on it and found something about OAuth. but most of the stuff out there is for iOS 5.
Have a look at the Social.framework (iOS6 and above). It manages authentication to several social networking sites, including twitter. Once the user has created an account and granted your app access to it, you can use SLRequest to perform authenticated twitter (or whatever) http requests without having to directly use Oauth.
First you get the ACAccount.
#import <Social/Social.h> // SLRequest
- (void)getTwitter {
ACAccountType *accountType = [_accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[_accountStore requestAccessToAccountsWithType:accountType options:nil completion:^(BOOL granted, NSError *error) {
if (granted) {
// access granted, get account info
NSArray *accounts = [_accountStore accountsWithAccountType:accountType];
ACAccount *account = [accounts lastObject];
// yay, now you can use account for authenticated twitter requests
} else {
NSLog(#"Access not granted: %#\n", error);
}
}
];
}
Then you can start making authenticated requests, e.g. get account info
- (void)getTwitterAccount:(ACAccount *)account {
NSString *get = #"https://api.twitter.com/1.1/account/verify_credentials.json";
NSURL *url = [NSURL URLWithString:get];
NSDictionary *parms = #{ #"include_entities" : #"false", #"skip_status" : #"true" };
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:parms ];
request.account = account;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error){
if(!error) {
NSLog(#"response: %#\n", [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);
} else {
NSLog(#"performRequestWithHandler error %#\n", error);
}
}];
}
See the Twitter API docs for timeline, tweets, etc.
I am developing an iOS app in which I have to invite to user Facebook Friends to join the app.
I am using Social Framework to do so. I have successfully posted on FB wall of logged in user but there is a problem in the message which I posted. the message says that "User has shared a link via sample app. Pleas join this awesome app.". I want the message:
"User -> Friend
Please join this awesome app.".
I want it like when it appears when we write on Friend FB Wall.
I have added the "to" parameter in which I am passing the friend's unique FB id. But it's not working.
Below is the code which I am using for this:
[accountStore requestAccessToAccountsWithType:facebookAccountType options:dict completion:^(BOOL granted, NSError *error)
{
if (granted)
{
__block ACAccount * facebookAccount;
NSDictionary *options = #{ ACFacebookAppIdKey: **FBAPPID**, ACFacebookPermissionsKey: permissions, #"ACFacebookAudienceKey": ACFacebookAudienceFriends };
[accountStore requestAccessToAccountsWithType:facebookAccountType options:options completion:^(BOOL granted, NSError *error)
{
if (granted)
{
NSArray *accounts = [accountStore accountsWithAccountType:facebookAccountType];
facebookAccount = [accounts lastObject];
NSURL *postURL = [NSURL URLWithString:#"https://graph.facebook.com/me/feed"];
NSMutableDictionary *postDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:
**FRIENDID**, #"to",**FRIENDNAME**, #"name",#"Testing of app.", #"caption", #"please join this awesome app.", #"message", nil];
SLRequest *postToMyWall = [SLRequest requestForServiceType:SLServiceTypeFacebook requestMethod:SLRequestMethodPOST URL:postURL parameters:postDict];
[postToMyWall setAccount:facebookAccount];
[postToMyWall performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error)
{
if (error) {
}
else
{
NSLog(#"Post successful");
NSString *dataString = [[NSString alloc] initWithData:responseData encoding:NSStringEncodingConversionAllowLossy];
NSLog(#"Response Data: %#", dataString);
[self performSelectorOnMainThread:#selector(postSuccess) withObject:nil waitUntilDone:NO];
}
}];
}
else
{
NSLog(#"rfc");
}
}];
}
else
{
[self performSelectorOnMainThread:#selector(showerrorAlert:) withObject:error waitUntilDone:NO];
}
}];
Please if anyone can give a solution for this. I can use Facebook Framework also but I need to authorize the user and fetch his/her friend list using the credentials stored in iPhone Device Settings. So if you have an alternate solution then please let me know.
I'm making an iPhone app where I get all feeds of a certain user. Now I was wondering if it's possible to do a retweet when you push a button? I'm using the social framework. After some searching through the social framework API, I didn't found anything.
Apple's limited Twitter API doesn't seem to cover retweets.
To retweet in iOS you would need to use Twitter's API
It looks like you would need to send the POST request yourself and it would look something like
http://api.twitter.com/1/statuses/retweet/3962807808.json // Taken from API page.
I've also found this SO post, but there doesn't seem to be an accepted answer
How to implement RETWEET in ios 5?
Here's some sample code for retweeting from Cocoanetics
- (void)_retweetMessage:(TwitterMessage *)message
{
NSString *retweetString = [NSString stringWithFormat:#"http://api.twitter.com/1/statuses/retweet/%#.json", message.identifier];
NSURL *retweetURL = [NSURL URLWithString:retweetString];
TWRequest *request = [[TWRequest alloc] initWithURL:retweetURL parameters:nil requestMethod:TWRequestMethodPOST];
request.account = _usedAccount;
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData)
{
NSError *parseError = nil;
id json = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:&parseError];
if (!json)
{
NSLog(#"Parse Error: %#", parseError);
}
else
{
NSLog(#"%#", json);
}
}
else
{
NSLog(#"Request Error: %#", [error localizedDescription]);
}
}];
}
EDIT: Keab42 pointed out the link is for the Twitter API which will be deprecated early next year. Here's the updated API page. https://dev.twitter.com/docs/api/1.1/get/statuses/retweets/%3Aid