how to Uploading image with text to facebook using FBRequestConnection? - objective-c

I am trying to upload the text with image using FBRequestConnection like as follow but I am only able to upload text,not the image.
But when I am giving any image link in place of img1(image) then I am able to see the image on the facebook wall.
UIImage *img1 = [UIImage imageNamed:#"Default#2x.png"];
NSMutableDictionary *params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
img1, #"picture",
#"Facebook SDK for iOS", #"name",
#"build apps.", #"caption",
#"imagae description.", #"description",
nil];
[params setObject:#"post message" forKey:#"message"];
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = #"Posted successfully.";
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
I have taken the two permission #"publish_actions",#"user_photos"
Please let me know where I am wrong in this code.

Check out my answer in the IOS Facebook SDK 3 upload image with message
It is the similar way which you required. Just add some more parameters as per your requirements.

Change #"picture" to #"source".
If you are using new Facebook 3.1 SDK you can do it simpler:
FBRequest *req = [FBRequest requestForUploadPhoto:img1];
[req.parameters addEntriesFromDictionary:[NSMutableDictionary dictionaryWithObjectsAndKeys:#"post message", #"message", nil]];
FBRequestConnection *con = [[FBRequestConnection alloc] init];
[con addRequest:req completionHandler....

Related

sign in/ Login Via twitter iOS7

it has been two weeks and I couldn't find a useful answer for my query, I've tried a lot of codes nothing had worked for me, Actually i am trying to build a log in page that able to user to sign in/log in from their Facebook or Twitter, its totally work for Facebook but the problem with twitter.
I've tried this code below please advice and help as I am still getting an error and the error is
(property twitterHandle not found on object of type "ViewController")
here is the code I've used.Note that I use Parse for my database.
*I've created an action button in the header called Twitter
-(IBAction)Twitter:(id)sender;
*and I had this code in the m file as showing below:
- (IBAction)Twitter:(id)sender {
{
// borrowed from: http://eflorenzano.com/blog/2012/04/18/using-twitter-ios5-integration-single-sign-on/
ACAccountStore *store = [[ACAccountStore alloc] init];
ACAccountType *twitterType = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
[store requestAccessToAccountsWithType:twitterType options:nil completion:^(BOOL granted, NSError *error)
{
if(granted) {
// Access has been granted, now we can access the accounts
// Remember that twitterType was instantiated above
NSArray *twitterAccounts = [store accountsWithAccountType:twitterType];
// If there are no accounts, we need to pop up an alert
if(twitterAccounts != nil && [twitterAccounts count] == 0)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"No Twitter Accounts"
message:#"There are no Twitter accounts configured. You must add or create a Twitter separately."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
} else {
ACAccount *account = [twitterAccounts objectAtIndex:0];
// Do something with their Twitter account
NSURL *url = [NSURL URLWithString:#"http://api.twitter.com/1/account/verify_credentials.json"];
SLRequest *req = [SLRequest requestForServiceType:SLServiceTypeTwitter
requestMethod:SLRequestMethodPOST
URL:url
parameters:nil];
// Important: attach the user's Twitter ACAccount object to the request
req.account = account;
[req performRequestWithHandler:^(NSData *responseData,
NSHTTPURLResponse *urlResponse,
NSError *error)
{
// If there was an error making the request, display a message to the user
if(error != nil) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Twitter Error"
message:#"There was an error talking to Twitter. Please try again later."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return;
}
// Parse the JSON response
NSError *jsonError = nil;
id resp = [NSJSONSerialization JSONObjectWithData:responseData
options:0
error:&jsonError];
// If there was an error decoding the JSON, display a message to the user
if(jsonError != nil)
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Twitter Error"
message:#"Twitter is not acting properly right now. Please try again later."
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alert show];
return;
}
NSString *screenName = [resp objectForKey:#"screen_name"];
self.twitterHandle = screenName;
PFUser *currentUser = [PFUser currentUser];
PFQuery *query = [PFQuery queryWithClassName:#"_User"];
[query whereKey:#"username" equalTo:currentUser.username];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// Do something with the found objects
for (PFObject *object in objects)
{
object[#"TwitterHandle"] = self.twitterHandle;
[object saveInBackground];
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}];
}
}
}];
}
}
Please Please Please help :(
(property twitterHandle not found on object of type "ViewController")
is telling you that somewhere, you are trying to access a property called twitterHandle on an object of type ViewController which has no such property.
I suspect the issue is in this line:
self.twitterHandle = screenName;
You just need to add a property to your view controller interface like this:
#property (nonatomic, strong) NSString *twitterHandle;

NSError and activating it while polling JSON data - Objective C

Trying to understand how/why NSError works in this case. I'm trying to do a simple UIAlertview when the JSON query returns no data (either the server is sending it or the user is not on internet). I have looked at about a dozen different answers and am just confusing myself more and more.
- (void)viewDidLoad
{
[super viewDidLoad];
dispatch_async(kBgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:
kLatestChartDataURL];
[self performSelectorOnMainThread:#selector(fetchedData:)
withObject:data waitUntilDone:YES];
});
}
- (void)fetchedData:(NSData *)responseData {
NSError *error = nil;
NSArray *theArray = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSDictionary *dict0 = [theArray objectAtIndex:147];
if (NO) {
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Data failed to load."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:#"Retry",nil];
[message show];
}
I've also tried:
if (!theArray) {
and
BOOL results = [NSArray etc...
Any thoughts on this would be appreciated, I've also looked at the developer docs and Cocoa is Mygirlfriend examples, and my brain has turned to mush at this point.
Try this
NSError *error = nil;
NSArray *theArray = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
if (!theArray) { // DO THIS CHECK
NSLog(#"error: %#", error);
UIAlertView *message = [[UIAlertView alloc] initWithTitle:#"Error"
message:#"Data failed to load."
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:#"Retry",nil];
[message show];
}
else
{
NSLog(#"parsed data");
    NSDictionary *dict0 = [theArray objectAtIndex:147];
}
If any error occurs while getting json from NSData then it will be recorded in object of NSError. So if this object is nil means there is no error while parsing json, and if that object holds value means there is some issue while parsing.

Twitter integration and iOS5: semantic and parsing issues

I was using some of Apple's example code to write the Twitter integration for my app.
However, I get a whopping amount of errors (mostly being Semantic and parse errors).
How can this be solved?
-(IBAction)TWButton:(id)sender {
ACAccountStore *accountstore = [[ACAccountStore alloc] init];
//Make sure to retrive twitter accounts
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:#"http://api.twitter.com/1/statuses/update.json"] parameters:[NSDictionary dictionaryWithObject:[#"Tweeted from iBrowser" forKey:#"status"] requestMethod:TWRequestMethodPOST];
[postRequest setAccount:twitterAccount];
[postRequest preformRequestWithHandeler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
NSString *output = [NSString stringWithFormat:#"HTTP response status: %i", [urlResponse statusCode]];
[self preformSelectorOnMainThread:#selector(displaytext:) withObject:output waitUntilDone:NO];
}];
}
}];
}
//Now lets see if we can actually tweet
-(void)canTweetStatus {
if ([TWTweetComposeViewController canSendTweet]) {
self.TWButton.enabled = YES
self.TWButton.alpha = 1.0f;
}else{
self.TWButton.enabled = NO
self.TWButton.alpha = 0.5f;
}
}
The first error I see is easy to get rid of.
Objective C convention is to make the first letters of each method name lower case.
Use makeKeyAndVisible in your AppDelegate.m
The other errors we'd probably need to see where (in your code) the errors are being thrown, not just what kind of errors.

Facebook iPhone SDK - automatically PublishSteam (bypass Post to wall dialog)

Trying to implement facebook wall post on the iphone app I'm working on.
How can I bypass the "Post to Your Wall" dialog box and just submit straight?
Basically I'm just trying to post a url and I don't really want to allow people to see that "Write something" textbox.
Here is the code that I have so far (from the sample app).
SBJSON *jsonWriter = [[SBJSON new] autorelease];
NSDictionary* actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:
#"Always Running",#"text",#"http://itsti.me/",#"href", nil], nil];
NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
NSDictionary* attachment = [NSDictionary dictionaryWithObjectsAndKeys:
#"a long run", #"name",
#"The Facebook Running app", #"caption",
#"it is fun", #"description",
#"http://itsti.me/", #"href", nil];
NSString *attachmentStr = [jsonWriter stringWithObject:attachment];
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Share on Facebook", #"user_message_prompt",
actionLinksStr, #"action_links",
attachmentStr, #"attachment",
nil];
[_facebook dialog:#"feed"
andParams:params
andDelegate:self];
Thank you,
Tee
Just use one of the - (FBRequest*)requestWith... instance methods of the Facebook class.
Simple wall post using the old REST API:
NSString *facebookStatusMessage = #"facebookStatusMessage";
NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
facebookStatusMessage, #"status",
nil];
FBRequest *request = [_facebook requestWithMethodName:#"status.set" andParams:params andHttpMethod:#"POST" andDelegate:self];
It's better to use the Facebook Graph API with - (FBRequest*)requestWithGraphPath: as the REST API will get deprecated.
Then also implement some of the FBRequestDelegate protocol:
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
}
- (void)request:(FBRequest *)request didLoad:(id)result {
// result may be a dictionary, an array, a string, or a number,
// depending on the format of the API response
}

Facebook Graph API Upload Photo Problem

I've searched all through the web and have downloaded the Facebook SDK thing to try out the upload photo function and it worked there.
Exact same codes over to my application and it doesn't work.
Help please???
These are my codes:
- (IBAction)pushUpload:(id)sender {
NSString *path = #"http://www.facebook.com/images/devsite/iphone_connect_btn.jpg";
NSURL *url = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img = [[UIImage alloc] initWithData:data];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, #"picture",
nil];
[_facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
[img release];
[loadingIcon startAnimating];
}
As you can see I've placed the loadingIcon there to start animating when its uploading.. and at the request didload i did the stopanimating command when it has successfully uploaded.
-(void)request:(FBRequest *)request didLoad:(id)result{
[loadingIcon stopAnimating];
if ([result isKindOfClass:[NSArray class]]) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"owner"]) {
[loadingIcon stopAnimating];
UIAlertView *alert;
alert = [[UIAlertView alloc] initWithTitle:#""
message:#"Photo uploaded."
delegate:self cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alert show];
[alert release];
} else {
// [self.label setText:[result objectForKey:#"name"]];
}
}
The thing is, the loading icon just keeps animating and no errors and all but still no picture uploaded to my facebook account. Any ideas why??
This are the codes in my .h file:
#interface UploadPhotosViewController :
UIViewController(FBRequestDelegate, FBDialogDelegate,
FBSessionDelegate){
IBOutlet UIImageView *imageView;
IBOutlet UIActivityIndicatorView *loadingIcon;
IBOutlet UIBarButtonItem *_pushPick;
IBOutlet UIBarButtonItem *_pushUpload;
Facebook * _facebook; }
#property(readonly) Facebook *facebook;
(IBAction)pushUpload:(id)sender;
(IBAction)pushPick:(id)sender;
//UINavigationControllerDelegate, UIImagePickerControllerDelegate,
#end
Another thing to note is that there are no colors indicator for the (FBRequestDelegate, FBDialogDelegate, FBSessionDelegate) when there are supposed to be.. is it a problem?
Check if you have written delegates of Facebook in your .h file.
Also check this code
It worked for me..
NSString *string=#"Images of me";
SBJSON *jsonWriter = [[SBJSON new] autorelease];
NSDictionary* attachment = [NSDictionary dictionaryWithObjectsAndKeys:
#"My name", #"name",
string, #"description", nil];
NSString *attachmentStr = [jsonWriter stringWithObject:attachment];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"This is image",#"description",
#"Share on Facebook", #"user_message_prompt",
//actionLinksStr, #"action_links",
attachmentStr, #"attachment",
/*Your image here", #"picture",
nil];
Try this code
Hope it helps....
Try me/feed instead of me/photos.
[_facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
I think it is because you're not declaring your protocols correctly. They go in angle brackets, not in parenthesis.
#interface UploadPhotosViewController : UIViewController<FBRequestDelegate, FBDialogDelegate, FBSessionDelegate>