How to post image with private tweet using SLRequest in iOS? - ios

I have a problem that I have some followers and I want to send a direct message with image to all followers but I didn't get a way to do that.
I study whole documentation but can't find a way to do that.
My code is here:
NSString *strUrl = #"https://api.twitter.com/1.1/direct_messages/new.json";
NSURL *url = [NSURL URLWithString:strUrl];
strUrl = nil;
NSMutableDictionary *parameters = [NSMutableDictionary new];
[parameters setValue:#"name" forKey:#"screen_name"];
[parameters setValue:#"123456" forKey:#"user_id"];
[parameters setValue:#"sending text" forKey:#"text"];
// Creating a request.
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:parameters];
NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://www.greenuplawnandsprinklers.com/uploads/design_sample_landscape.jpg"]];
[request addMultipartData:imageData
withName:#"media[]"
type:#"image/jpeg"
filename:#"image.jpg"];
imageData = nil;
[request setAccount:twitAccount];
url = nil;
parameters = nil;
// Perform the request.
[request performRequestWithHandler:^(NSData *responseData,NSHTTPURLResponse *urlResponse,NSError *error)
{
dispatch_async(dispatch_get_main_queue(), ^{
// Check if we reached the rate limit.
if ([urlResponse statusCode] == 429)
{
NSLog(#"Rate limit reached");
return;
}
if(LOGS_ON) NSLog(#"TwitterFriendModel-->shareMagazineTitle-->error = %#",error);
// Check if there is some response data.
if (responseData)
{
NSError *error = nil;
NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingMutableLeaves error:&error];
NSLog(#"dictionary = %#",dictionary);
dictionary = nil;
}
});
}];
}
I saw all other similar question/answers on stackoverflow but I didn't get a way to send direct message with image to followers.
Please don't consider this question as duplicate and try to resolve my problem. I will appreciate your every clue.

Here is my code to accomplish this task, it works for me.. hope also helpfull for you..
NSDictionary *message = #{#"status": messagetext};
NSURL *requestURL = [NSURL
URLWithString:#"https://upload.twitter.com/1/statuses/update_with_media.json"];
SLRequest *postRequest = [SLRequest
requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:requestURL parameters:message];
UIImage *image = [self imageReduceSize:[UIScreen mainScreen].bounds.size:imgPost.image];
NSData *myData = UIImagePNGRepresentation(image);
[postRequest addMultipartData:myData withName:#"media" type:#"image/png" filename:#"TestImage"];

Related

ios - update UI inside block

I make a call to the youtube API to get the title of a video. I then want to display the title of the video on the screen in a table. How do I access the title after the block has finished executing?
Here's the code to get the title
-(void)getVideoTitle:(NSString *)urlStr success:(void (^)(NSDictionary *responseDict))success{
urlStr = [NSString stringWithFormat:#"https://www.googleapis.com/youtube/v3/videos?part=contentDetails%%2C+snippet%%2C+statistics&id=%#&key={API_KEY}",urlStr];
NSURL *url = [[NSURL alloc] initWithString:urlStr];
// Create your request
NSURLRequest *request = [NSURLRequest requestWithURL:url];
// Send the request asynchronously
[[[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *connectionError) {
// Callback, parse the data and check for errors
if (data && !connectionError) {
NSError *jsonError;
NSDictionary *jsonResult = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&jsonError];
if (!jsonError) {
success(jsonResult);
// NSLog(#"Response from YouTube: %#", jsonResult);
}
}
}] resume];
}
Here's how I call the above function:
[self getVideoTitle:#"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:#"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:#"snippet"];
NSString *title = [snippet valueForKey:#"title"];
}];
How do I get access the title variable outside the block after the block has finished executing?
I have tried the following with no luck
dispatch_async(dispatch_get_main_queue(), ^{
[self updateMyUserInterfaceOrSomething];
});
In your code:
NSString* recievedTitle __block = nil; //title is here, after block below run
[self getVideoTitle:#"zB4I68XVPzQ" success:^(NSDictionary *responseDict){
NSArray *itemsArray = [responseDict valueForKey:#"items"];
NSDictionary *item = itemsArray[0];
NSDictionary* snippet = [item valueForKey:#"snippet"];
recievedTitle = [snippet valueForKey:#"title"]; //here you write it
// or
NSString *title = [snippet valueForKey:#"title"];
[self updateInterfaceWithTitle: title]
}];
///
- (void)updateInterfaceWithTitle:(NSString*)title{
//use title here
}

Objective-C Facebook video sharing for the app

I'm very much new to objective-c. Basically, all I see is black right now. I'm assigned to code the facebook sharing part of the app we're making, and believe me, I've tried almost all tutorials (none worked, I've tried) and went through the questions here in stack, and I still couldn't upload. So please, someone help?
How to upload videos to facebook via the app? Please provide sample code if you have.
Here is the code I'm trying right now:
-(void)post
{
NSURL *videourl = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"Here's to the Crazy Ones" ofType:#"mp4"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSLog(#"PATH: %#", filePath);
NSDictionary *params = #{
#"title": #"uploading",
#"description": #"testing..."
};
NSLog(#"uploading...");
SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:videourl
parameters:params];
[uploadRequest addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[pathURL absoluteString]];
NSLog(#"Here it goes...");
uploadRequest.account = self.facebookAccount;
NSLog(#"Past uploadrequest...");
[FBSession setActiveSession:FBSession.activeSession];
[uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
// [FBSession setActiveSession:FBSession.activeSession];
if (!FBSession.activeSession.isOpen) {
// [FBSession openActiveSessionWithAllowLoginUI: YES];
[FBSession setActiveSession:FBSession.activeSession];
}
NSLog(#"response string: %#", responseString);
NSLog(#"Here I am...");
if(error){
NSLog(#"Error %#", error.localizedDescription);
}else
NSLog(#"%#", responseString);
}];
}
With this I'm getting an error of:
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
Here I provide a link which will guide you step step to upload video to FB Tutorial

Upload video to Facebook doesn't work with SLRequest

I was trying to upload the video to Facebook with following code:
- (void)facebok
{
self.accountStore = [[ACAccountStore alloc]init];
ACAccountType *FBaccountType= [self.accountStore accountTypeWithAccountTypeIdentifier:#"com.apple.facebook"];
NSDictionary *options = #{
ACFacebookAppIdKey: #"appid",
ACFacebookPermissionsKey: #[#"publish_stream"],
ACFacebookAudienceKey: ACFacebookAudienceFriends
};
[self.accountStore requestAccessToAccountsWithType:FBaccountType options:options completion:
^(BOOL granted, NSError *e) {
if (granted) {
NSArray *accounts = [self.accountStore accountsWithAccountType:FBaccountType];
//it will always be the last object with single sign on
self.facebookAccount = [accounts lastObject];
NSLog(#"facebook account =%#",self.facebookAccount);
[self post];
} else {
//Fail gracefully...
NSLog(#"error getting permission %#",e);
}
}];
}
- (void)post
{
NSURL *url = [NSURL URLWithString:#"https://graph.facebook.com/me/videos"];
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"test" ofType:#"mov"];
NSURL *pathURL = [[NSURL alloc]initFileURLWithPath:filePath isDirectory:NO];
NSData *videoData = [NSData dataWithContentsOfFile:filePath];
NSString *status = #"One step closer.";
NSDictionary *params = #{#"title":status, #"description":status};
SLRequest *uploadRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodPOST
URL:url
parameters:params];
[uploadRequest addMultipartData:videoData
withName:#"source"
type:#"video/quicktime"
filename:[pathURL absoluteString]];
uploadRequest.account = self.facebookAccount;
[uploadRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
if(error){
NSLog(#"Error %#", error.localizedDescription);
}else
NSLog(#"%#", responseString);
}];
}
Fist it ask for the permission to post the video. That is fine but after few seconds it gives me this error:
{"error":{"message":"You recently posted something that violates Facebook policies, so you're temporarily blocked from using this feature. For more information, visit the Help Center.\n\nTo keep from getting blocked again, please make sure you've read and understand Facebook's Community Standards.","type":"OAuthException","code":368}}
Am I doing something wrong to post the video on Facebook?

My code for paging through Twitter friends using recursion not working - iOS

I'm trying to page through a user's twitter friends using cursors. Since you get 20 at a time along with a next cursor, I thought perhaps recursion was the best way to handle this. However, I believe because I'm using completion handler blocks, it isn't working correctly. I keep getting just two pages of friends (40), and it returns.
- (void)fetchTwitterFriendsForCrush:(Crush*)crush
fromCursor:(NSString*)cursor
usingManagedObjectContext:(NSManagedObjectContext*)moc
withSender:(id) sender
usingCompletionHandler:(void(^)())completionHandler
{
// twitter returns "0" when there are no more pages to receive
if (([cursor isEqualToString:#"0"]) || (cursor == nil)) {
completionHandler();
return;
}
NSString *urlString =
[NSString stringWithFormat:#"https://api.twitter.com/1.1/friends/list.json?cursor%#skip_status=1", cursor];
NSURL *requestURL = [NSURL URLWithString:urlString];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodGET
URL:requestURL
parameters:nil];
request.account = self.twitterAccount;
[request performRequestWithHandler:
^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (error) {
NSLog(#"Error getting twitter friends = %#", error);
}
if (responseData) {
NSError *jsonError;
NSString *nextCursor = nil;
NSMutableArray *friendsArray = [NSMutableArray arrayWithCapacity:100];
NSDictionary *friendsDictionary =
[NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&jsonError];
if ([friendsDictionary valueForKey:#"next_cursor_str"]) {
nextCursor = [friendsDictionary valueForKey:#"next_cursor_str"];
}
if ([friendsDictionary valueForKey:#"users"]) {
[friendsArray addObjectsFromArray:[friendsDictionary valueForKey:#"users"]];
}
for (NSDictionary *singleFriend in friendsArray) {
NSString *twitterID = [singleFriend valueForKey:#"id_str"];
NSString *name = [singleFriend valueForKey:#"name"];
NSString *screenName = [singleFriend valueForKey:#"screen_name"];
dispatch_queue_t mainQueue = dispatch_get_main_queue();
dispatch_async(mainQueue, ^(void) {
// update model
TwitterFriend *newTwitterFriend =
[TwitterFriend twitterFriendWithTwitterID:twitterID
forCrush:crush
usingManagedObjectContext:moc];
newTwitterFriend.name = name;
newTwitterFriend.screenName = screenName;
});
}
[self fetchTwitterFriendsForCrush:crush
fromCursor:nextCursor
usingManagedObjectContext:moc
withSender:self
usingCompletionHandler:nil];
}
}];
}
And the method that calls it:
[self.twitterNetwork fetchTwitterFriendsForCrush:self.crush fromCursor:#"-1" usingManagedObjectContext:self.managedObjectContext withSender:self usingCompletionHandler:^{
//
[self reloadData];
}];
UPDATE: It appears that I'm receiving the same next_cursor data on every request. Has anyone experienced this? Or do you see anything in this code that would cause that?
I found that a more complex way is better. You may use https://api.twitter.com/1.1/friends/ids.json? to get your friends ids list. Then using 1.1/users/lookup.json you may get the full info for users. I wrote a small helper to drill down user friends with SLRequest (#iOS6) https://github.com/ArchieGoodwin/NWTwitterHelper

Get current user's info from Twitter API

I am building a Twitter app (with oAuth) and I cannot find any info on how I can get the current user's info.
By current user, I mean the user which granted my app permissions and for whom the app is making the requests to the API.
Any suggestions?
It was actually "account/verify_credentials" as seen here:
https://developer.twitter.com/en/docs/accounts-and-users/manage-account-settings/api-reference/get-account-verify_credentials.html
Link to the documentation for API v. 1.1: https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials
Using oAuth you are able to make calls to get user info from your TwitterOAuth object.
e.g if
$oauth = new TwitterOAuth([keys here]);
$credentials = $oauth->get('account/verify_credentials');
echo "Connected as #" . $credentials->screen_name ."\n";
Solution respecting iOS:
1) If you have a Twitter account (i.e. ACAccount from ACAccountStore) on your device, the only thing you need is to attach it to SLRequest and get all the user info from the returned dictionary:
NSURL *url = [NSURL URLWithString:#"https://api.twitter.com/1.1/account/verify_credentials.json"];
NSMutableDictionary *params = [NSMutableDictionary new];
[params setObject:[Twitter sharedInstance].session.userID forKey:#"user_id"];
[params setObject:#"0" forKey:#"include_entities"];
[params setObject:#"1" forKey:#"skip_status"];
[params setObject:#"1" forKey:#"include_email"];
SLRequest *request = [SLRequest requestForServiceType:SLServiceTypeTwitter requestMethod:SLRequestMethodGET URL:url parameters:params];
[request setAccount:twitterAccount]; //one of the Twitter Acc
[request performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
NSDictionary *twitterData = [NSJSONSerialization JSONObjectWithData:responseData options:NSJSONReadingAllowFragments error:NULL];
});
}else {
NSLog(#"Error while downloading Twitter user data: %#", error);
}
}];
2) Otherwise - you need to send OAuth (X-Auth) user credentials. The easiest way is to use TWTROAuthSigning class to retrieve OAuth-params:
TWTROAuthSigning *oauthSigning =
[[TWTROAuthSigning alloc]
initWithAuthConfig:
[Twitter sharedInstance].authConfig
authSession:session];
NSDictionary *authHeaders =
[oauthSigning OAuthEchoHeadersToVerifyCredentials];
and than send the ordinary request attaching credentials as header fields:
NSString *oauthParameters = authHeaders[#"X-Verify-Credentials-Authorization"];
NSString *urlString = authHeaders[#"X-Auth-Service-Provider"];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlString]];
request.allHTTPHeaderFields = #{#"Authorization":oauthParameters};
[request setHTTPMethod:#"GET"];
NSOperationQueue *queue = [[NSOperationQueue alloc]init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response,NSData *data,NSError *error){
NSDictionary *twitterData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:NULL];
}];
If you support an old version of Twitter SDK or searching for more options I'd recommend to look at STTwitter lib

Resources