iOS: Facebook error "missing message or attachment" - facebook

Upgrading my app. Target is iOS5.1. Xcode 4.5.2 and am using FacebookSDK 3.0 along with Twitter Frameworks.
App is logging into Facebook without issue. When I attempt to publish a post, I get this returned in the log:
2012-12-18 10:39:31.934 MyApp[31754:1d603] Error Domain=com.facebook.sdk Code=5
"The operation couldn’t be completed. (com.facebook.sdk error 5.)"
UserInfo=0xab74630 {com.facebook.sdk:ParsedJSONResponseKey={
body = {
error = {
code = 100;
message = "(#100) Missing message or attachment";
type = OAuthException;
};
};
code = 400;
}, com.facebook.sdk:HTTPStatusCode=400}
2012-12-18 10:39:31.935 MyApp[31754:1d603] (null)
This last line is the result of a log expression to list the "postParams" in the "publishStory" method listed below. Note that it is (null).
The error result in simulator is "error: domain = com.facebook.sdk, code = 5"
I used the Facebook tutorial to build the FB interface. I've got the params listed in initWithNibName, just as the tutorial indicates.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// this stuff will change... just get it working
self.postParams = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"Share...", #"message",
#"http://MyApp.com", #"link",
#"icon.png", #"picture",
#"MyApp", #"name",
#"A wonderful way to record your life events.", "caption",
#"Easy to use.", #"description",
nil];
}
return self;
}
Then, the "publish" is in a separate method, which is where it stops and I get the above error.
- (void)publishStory
{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:_postParams
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
NSLog(#"%#",error);
NSLog(#"%#", _postParams);
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = [NSString stringWithFormat:
#"Posted action, id: %#",
[result objectForKey:#"id"]];
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
}
I think, that the actual params are not being uploaded. I've been searching for several days trying to find a solution.
Anyone have an idea of how to fix this and get the post to complete? Any help would be greatly appreciated!

I Had a similar problem, but my problem was that the postParams weren't retained because I didn't use a property and I was creating the postParams in the same publish method. The parameters need to me retained somewhere in the class.
Assure that your property is using retain, also make sure that the init method is being called.

Related

Error 204, The Request Did not Return any Content While Posting data to Twitter

I tried to post from twitter but it not posting the comments. It display an error 204 , in the facebook the same data is successfully posted but in the twitter i got an error can any one have an idea How to solve it
-(void)postDataOnTwitterMethod{
if ([[FHSTwitterEngine sharedEngine]isAuthorized]) {
NSData *dataFromPath = UIImageJPEGRepresentation(cameraImage,1.0);
number = (arc4random()%10000)+1; //Generates Number from 1 to 10000.
RndNo = [NSString stringWithFormat:#"%i", number];
NSLog(#" ITEM %#",RndNo);
NSString *avalabelDate = [NSString stringWithFormat:#"%#_%#",[CommonMethods getCurrentDateAndTime],self.AvailableTillTextField.text];
NSString *theWholeString = [NSString stringWithFormat:#"Item No: %#\nItemName: %#\nItemCost: %#\nAvailableTill: %#\nCategory: %#\nDescription: %#",RndNo,self.NameTextField.text,self.PriceTextField.text,avalabelDate,self.ListTypeTextField.text,self.DecTextView.text];
dispatch_async(GCDBackgroundThread, ^{
#autoreleasepool {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSError *returnCode = [[FHSTwitterEngine sharedEngine]postTweet:theWholeString withImageData:dataFromPath];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSString *title = nil;
NSString *message = nil;
if (returnCode) {
title = [NSString stringWithFormat:#"Error %d",returnCode.code];
message = returnCode.localizedDescription;
} else {
title = #"Tweet Posted";
}
dispatch_sync(GCDMainThread, ^{
#autoreleasepool {
UIAlertView *av = [[UIAlertView alloc]initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[av show];
}
});
}
});
}
else{
[[FHSTwitterEngine sharedEngine]showOAuthLoginControllerFromViewController:self withCompletion:^(BOOL success) {
NSLog(success?#"L0L success":#"O noes!!! Loggen faylur!!!");
}];
}
}
Your comments made me smile.
I believe it's an HTML error. It means the data was received and understood but you shouldn't expect a return. In other words, it's void. At least that's what I can see with a quick look around your code and my minimal understanding of Twitter API.
Now i am able to send the String but cant able to send the Image using this method
NSError *returnCode = [[FHSTwitterEngine sharedEngine]postTweet:theWholeString withImageData:imageData];
FHSTwitterEngine has some known bugs, and the problem is now fixed, see below:
Getting error while posting image using FHSTwitterEngine
compress the existing image with this code and you will get images posted.
NSData *data = UIImageJPEGRepresentation(imageView.image, 0.6);

Does not receive any "Request" after sending out from iOS Facebook SDK

I'm following these two tutorials in Facebook developer website
https://developers.facebook.com/docs/tutorials/ios-sdk-games/requests/
https://developers.facebook.com/docs/howtos/send-requests-using-ios-sdk/#step2
These are my codes:
[FBWebDialogs presentRequestsDialogModallyWithSession:nil
message:[NSString stringWithFormat:#"I just smashed %u friends! Can you beat it?", score]
title: nil
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error)
{
if (error)
{
// Case A: Error launching the dialog or sending request.
UIAlertView* alert = [[UIAlertView alloc] initWithTitle: #"Facebook" message: error.description delegate: nil cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[alert show];
[alert release];
}
else
{
if (result == (FBWebDialogResultDialogCompleted))
{
// Handle the publish feed callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if ([urlParams valueForKey: #"request"])
{
// User clicked the Share button
NSLog(#"Send");
}
}
}
}];
Problem is after I send out the request, my friend told me that he doesn't receive any notification/request in FB Notification Center site. Does anyone know why?
These are the things I've done:
I've setup properly in info.plist and the Facebook App.
I'm not using Sandbox mode.
My current application is able to log in and post to wall.
I've publish_actions permission.
I did not received any error or warning.
I found my solution here:
Facebook App Requests aren't shown on iOS devices?
It is because I didn't set the iPhone App ID and iPad App ID
Use following method, it will help you :
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
//Added by Rigel Networks July 2, 2013 to solve Facebook Cancel button popup issue
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}

How to post to a users wall using Facebook SDK

I want to post some text to a users wall using the facebook sdk in an iOS app.
Is posting an open graph story now the only way to do that?
I've found with open graph stories they are really strange, you can only post things in the format "user x a y" where you preset x and y directly on facebook, like user ata a pizza or user played a game. Setting up each one is pretty laborious too because you have to create a .php object on an external server for each one.
Am I missing something or is there a simpler way to go about this?
Figured it out by browsing the facebook tutorials a bit more.
-(void) postWithText: (NSString*) message
ImageName: (NSString*) image
URL: (NSString*) url
Caption: (NSString*) caption
Name: (NSString*) name
andDescription: (NSString*) description
{
NSMutableDictionary* params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
url, #"link",
name, #"name",
caption, #"caption",
description, #"description",
message, #"message",
UIImagePNGRepresentation([UIImage imageNamed: image]), #"picture",
nil];
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
// No permissions found in session, ask for it
[FBSession.activeSession requestNewPublishPermissions: [NSArray arrayWithObject:#"publish_actions"]
defaultAudience: FBSessionDefaultAudienceFriends
completionHandler: ^(FBSession *session, NSError *error)
{
if (!error)
{
// If permissions granted and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}];
}
else
{
// If permissions present and not already posting then publish the story
if (!m_postingInProgress)
{
[self postToWall: params];
}
}
}
-(void) postToWall: (NSMutableDictionary*) params
{
m_postingInProgress = YES; //for not allowing multiple hits
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error)
{
if (error)
{
//showing an alert for failure
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Post Failed"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
m_postingInProgress = NO;
}];
}
the easiest way of sharing something from your iOS app is using the UIActivityViewController class, here you can find the documentation of the class and here a good example of use. It is as simple as:
NSString *textToShare = #”I just shared this from my App”;
UIImage *imageToShare = [UIImage imageNamed:#"Image.png"];
NSURL *urlToShare = [NSURL URLWithString:#"http://www.bronron.com"];
NSArray *activityItems = #[textToShare, imageToShare, urlToShare];
UIActivityViewController *activityVC = [[UIActivityViewController alloc]initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:activityVC animated:TRUE completion:nil];
This will only work on iOS 6 and it makes use of the Facebook account configured in the user settings, and the Facebook SDK is not needed.
You can use Graph API as well.
After all the basic steps to create facebook app with iOS, you can start to enjoy the functionality of Graph API. The code below will post "hello world!" on your wall:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
...
//to get the permission
//https://developers.facebook.com/docs/facebook-login/ios/permissions
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
NSLog(#"publish_actions is already granted.");
} else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result.
}];
}
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[[[FBSDKGraphRequest alloc]
initWithGraphPath:#"me/feed"
parameters: #{ #"message" : #"hello world!"}
HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"Post id:%#", result[#"id"]);
}
}];
}
...
The basic staff is presented here: https://developers.facebook.com/docs/ios/graph
The explorer to play around is here:
https://developers.facebook.com/tools/explorer
A good intro about it: https://www.youtube.com/watch?v=WteK95AppF4

ObjectiveFlickr Photo Upload Error

I'm working on using the ObjectiveFlickr library to upload photos to Flickr from my iPhone app. I am able to authorize the app and perform general requests, but I am getting an error while trying to upload a photo. The photo is meant to be uploaded is an image captured using AVFoundation. Here is the relevant code:
UIImage *image = [[UIImage alloc] initWithData:imageData];
if ([[AppDelegate sharedDelegate].apiContext.OAuthToken length]) {
NSData *uploadData = UIImageJPEGRepresentation(image, 1);
if (!flickrRequest) {
flickrRequest = [[OFFlickrAPIRequest alloc] initWithAPIContext:[AppDelegate sharedDelegate].apiContext];
flickrRequest.delegate = self;
flickrRequest.requestTimeoutInterval = 60.0;
}
[flickrRequest uploadImageStream:[NSInputStream inputStreamWithData:uploadData] suggestedFilename:#"Test" MIMEType:#"image/jpeg" arguments:[NSDictionary dictionaryWithObjectsAndKeys:#"0", #"is_public", nil]];
[UIApplication sharedApplication].idleTimerDisabled = YES;
NSLog(#"Can upload photo");
The flickrRequest object is defined and #property'd in the .h file pertaining to the code above.
The OFFlickrRequestDelegate methods are as follows:
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest imageUploadSentBytes:(NSUInteger)inSentBytes totalBytes:(NSUInteger)inTotalBytes {
NSLog(#"Success");
}
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didCompleteWithResponse:(NSDictionary *)inResponseDictionary {
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inResponseDictionary);
}
- (void)flickrAPIRequest:(OFFlickrAPIRequest *)inRequest didFailWithError:(NSError *)inError {
NSLog(#"%s %# %#", __PRETTY_FUNCTION__, inRequest.sessionInfo, inError);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Error" message:[inError description] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert show];
}
When I run the project on the device the console shows:
Can upload photo
Success
Success
Success
Success
flickrAPIRequest:didFailWithError:(null) Error Domain=org.lukhnos.ObjectiveFlickr Code=2147418115 "The operation couldn’t be completed. (org.lukhnos.ObjectiveFlickr error 2147418115.)"
Searching through the API's documentation, "error 2147418115" is defined as "OFFlickrAPIRequestFaultyXMLResponseError". I'm not really sure what this means though. Also strange--"Success" appears four times when I'm only attempting to upload one photo.
The sample app utilizing ObjectiveFlickr, "Snap and Run" uploads photos fine on the same device that I am testing on. Comparing the code between my app and Snap and Run, I don't see any major differences that could cause the photo not to upload.
Any help would be greatly appreciated.
That is strange. OFFlickrAPIRequestFaultyXMLResponseError means the returned data cannot be parsed as XML. If the sample app SnapAndRun runs correctly and yours don't, I suggest add one line in ObjectiveFlickr.m, right after the line NSString *stat = [rsp objectForKey:#"stat"];:
NSString *dataString = [[[NSString alloc] initWithData:[request receivedData] encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"received response: %#", dataString);
This may help you find out what goes wrong (e.g. if it's a server-side issue, or some response format that the library missed).
When I got this error I used Charles to see what was going on. Flickr was sending back an error saying that the signature was invalid. Looking at my request, I found that I had reversed the order of the key and values (i.e. there was whitespace in one of my keys, which probably caused a signature error).

GData Picasa Photo Album iPhone

I was hoping someone could help me with this problem. I am trying to access a Picasa Web Album from my iphone application. I have used GData previously with Google Calendar and getting events and the data related to them before, so I set up my methods in a similar fashion. I however am getting an error that is telling me the following
serviceBase:<GDataServiceGooglePhotos: 0x4d4e6d0> objectFetcher:<GDataHTTPFetcher: 0xbaa35c0> failedWithStatus:400 data:Too many results requested
I am think that I have narrowed down the problem that I am having has something to do with the ticket that I am using, in the following line
ticket = [service fetchFeedWithURL:[NSURL URLWithString:kGDataGooglePhotosAllFeed]
delegate:self
didFinishSelector:#selector(photosListTicket:finishedWithFeed:error:)];
I however am unable to get past this problem. Does anyone have a suggestion to get past this problem. Am I doing something wrong?
My full code for the retrieval of the pictures is shown below. Anywhere that says picAlbum, that is a predefined NSArray to hold the information.
- (GDataServiceGooglePhotos *)photoService {
static GDataServiceGooglePhotos* service = nil;
if (!service) {
service = [[GDataServiceGooglePhotos alloc] init];
[service setShouldCacheDatedData:YES];
[service setServiceShouldFollowNextLinks:YES];
}
[service setUserCredentialsWithUsername:#"username"
password:#"password"];
return service;
}
-(void)loadGooglePhotos {
[self fetchAllPhotos];
}
-(void)fetchAllPhotos {
NSLog(#"In fetchAllPhotos");
GDataServiceGooglePhotos *service = [self photoService];
GDataServiceTicket *ticket;
ticket = [service fetchFeedWithURL:[NSURL URLWithString:kGDataGooglePhotosKindAlbum]
delegate:self
didFinishSelector:#selector(photosListTicket:finishedWithFeed:error:)];
}
- (void)photosListTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataFeedPhotoAlbum *)feed error:(NSError *)error {
NSLog(#"In photosListTicket");
NSArray *photos = [feed entries];
if ([photos count] != 0){
self.picAlbum = [photos objectAtIndex:0];
NSLog(#"fetching photos");
[self fetchPhotos];
}
else {
NSLog(#"User has no photos...");
}
}
- (void)fetchPhotos {
NSLog(#"In fetchPhotos");
if (self.picAlbum) {
NSURL *feedURL = [[self.picAlbum alternateLink] URL];
if (feedURL) {
NSLog(feedURL);
GDataQueryGooglePhotos *query = [GDataQueryGooglePhotos photoQueryWithFeedURL:feedURL];
[query setMaxResults:1000];
GDataServiceGooglePhotos *service = [self photoService];
GDataServiceTicket *ticket;
ticket = [service fetchFeedWithQuery:query delegate:self didFinishSelector:#selector(photosEventsTicket:finishedWithFeed:error:)];
}
}
}
- (void)photosEventsTicket:(GDataServiceTicket *)ticket finishedWithFeed:(GDataFeedPhotoAlbum *)feed error:(NSError *)error {
NSLog(#"In photosEventsTicket");
NSArray *photos = [feed entries];
NSLog([NSString stringWithFormat:#"%i",[photos count]]);
}
Thanks in advance for any information or help that you can provide.
If the server says "Too many results requested" that's a clue that the max results query parameter is too big.
The fetches in the code snippet do not appear functional. Neither kGDataGooglePhotosKindAlbum nor an album's alternateLink would be URLs for feeds.