So I'm creating an iPhone app that needs to be able to upload a photo when the user checks into a location using the Facebook Graph API.
Right now my code is this:
if (![delegate.facebook isSessionValid])
[delegate.facebook authorize:[NSArray arrayWithObjects:#"publish_stream", #"offline_access", #"publish_checkins", nil]];
parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:[placeDictionary objectForKey:#"id"] , #"place",
serialisedCoordinates, #"coordinates",
message, #"message",
pickedImage, #"picture",
#"Via the official REDACTED app", #"application", nil];
[delegate.facebook requestWithGraphPath:#"me/checkins" andParams:parameters andHttpMethod:#"POST" andDelegate:fbCheckInResultHandler];
Where 'pickedImage' is the UIImage returned from a UIImagePickerController.
Even when I pick an image (i.e., pickedImage != nil), no picture is uploaded when checked in. The check in appears on Facebook with the message, coordinates and app information, just no image.
Really hope someone can help.
Cheers,
Kiran
Here is the whole function that is being called when a checkin is made:
-(void)fbPostCheckInWithMessage:(NSString *)message andFriends:(NSArray *)friends {
if (![delegate.facebook isSessionValid]) {
NSLog(#"Session invalid");
[delegate.facebook authorize:[NSArray arrayWithObjects:#"publish_stream", #"offline_access", #"publish_checkins", nil]];
} else {
NSLog(#"Session valid");
}
NSMutableString *friendsIDString;
friendsIDString = [NSMutableString stringWithFormat:#"%#", [[friends objectAtIndex:0] userID]];
if ([friends count] > 1) {
for (User *f in taggedFriends) {
if (f != [taggedFriends objectAtIndex:0]) {
[friendsIDString appendString:[NSString stringWithFormat:#", %#", f.userID]];
}
}
}
NSLog(#"Tagged Friends: %#", friendsIDString);
SBJSON *jsonWriter = [SBJSON new];
NSMutableDictionary *locationDictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:#"%f", userLocation.coordinate.latitude], #"latitude",
[NSString stringWithFormat:#"%f", userLocation.coordinate.longitude], #"longitude", nil];
NSString *serialisedCoordinates = [jsonWriter stringWithObject:locationDictionary];
NSData *pictureData = UIImagePNGRepresentation(pickedImage);
NSLog(#"picture: %#", pictureData);
NSMutableDictionary *parameters = [NSMutableDictionary dictionaryWithObjectsAndKeys:[placeDictionary objectForKey:#"id"] , #"place",
serialisedCoordinates, #"coordinates",
pictureData, #"message",
pickedImage, #"picture",
#"Via the official REDACTED app", #"application", nil];
[delegate.facebook requestWithGraphPath:#"me/checkins" andParams:parameters andHttpMethod:#"POST" andDelegate:fbCheckInResultHandler];
}
I am using the friendsIDString to get the IDs of the friends the user with. I've removed this functionality from the example here because it was all commented out because I was trying to isolate what was causing the problem (which was the photo tagging). Just wanted to clear that up.
--UPDATE--
Here's how I'm setting pickedImage. I use the delegate methods from the UIImagePickerController:
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary *)editingInfo {
NSLog(#"Picked image");
pickedImage = [[UIImage alloc] init];
pickedImage = image;
[imagePickerController dismissModalViewControllerAnimated:YES];
}
You can upload photos to facebook using :- UIImagePNGRepresentation,UIImageJPEGRepresentation,etc based on type of image or imagewithdata from UIImage class..
NSData *yourImageData= UIImagePNGRepresentation(yourImage);
Initialize the dictionary :-
NSMutableDictionary *mutableDictWithParam= [NSMutableDictionary dictionaryWithObjectsAndKeys:#"Your text", #"message", yourImageWithData, #"theSource", nil];
finally send post :-
[facebook requestWithGraphPath:#"/me/photos" andParams:mutableDictWithParam andHttpMethod:#"POST" andDelegate:self];
In you app i think you have not initialized your NSData object(pickedimage) ..else everything seems fine.
As Per Our Discussion You can use this to compress image:-
NSData* UIImageJPEGRepresentation(UIImage *image, CGFloat compressionQuality);
NSData *compressedImage = UIImagePNGRepresentation(yourIMage, .5)//quality is ensured through second argument lies between o and 1
Related
I can't seem to work out how to tag users in a Facebook photo upload.
The documentation seems to suggest that you use an array, but the following code doesn't parse correctly (causes an application crash)
- (void)uploadImage:(UIImage *)img
withTags:(NSArray *)tags
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"msgstring", #"message",
img, #"picture",
nil];
if (tags) {
[params setObject:tags
forKey:#"tags"];
}
self.requestType = FBAssistantRequestImageUpload;
[self.facebook requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
It works fine without the tags. The array at the moment contains a single string with the identifier of the friend I wish to tag.
I assume I'm adding the tags incorrectly. I was hoping to avoid having to use the three-step method outlined here: Tag Friends in Facebook Photo Upload, as I believe that requires photos permission, which just posting the photo doesn't need.
here's the code I use to tag friends on photos:
NSMutableArray *tags = [[NSMutableArray alloc] init];
NSString *tag = nil;
if(self.selectedFriends != nil){
for (NSDictionary *user in self.selectedFriends) {
tag = [[NSString alloc] initWithFormat:#"{\"tag_uid\":\"%#\"}",[user objectForKey:#"id"] ];
[tags addObject:tag];
}
NSString *friendIdsSeparation=[tags componentsJoinedByString:#","];
NSString *friendIds = [[NSString alloc] initWithFormat:#"[%#]",friendIdsSeparation ];
[params setObject:friendIds forKey:#"tags"];
}
How can I upload a photo to facebook from an iOS app using their new API/SDK? I've already tried and I'm not getting anywhere, just keep running in circles. Here is the code I currently have:
-(void)dataForFaceboo{
self.postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
self.uploadPhoto.image, #"picture", nil];
}
-(void)uploadToFacebook{
[self dataForFacebook];
NSLog(#"Going to facebook: %#", self.postParams);
// Hide keyboard if showing when button clicked
if ([self.photoCaption isFirstResponder]) {
[self.photoCaption resignFirstResponder];
}
// Add user message parameter if user filled it in
if (![self.photoCaption.text
isEqualToString:kPlaceholderPostMessage] &&
![self.photoCaption.text isEqualToString:#""])
{
[self.postParams setObject:self.photoCaption.text forKey:#"message"];
}
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.postParams
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 = [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];
}];
}
Your code is fine, some slight changes to be done:
add the image to the dictionary in NSData format, like
[params setObject:UIImagePNGRepresentation(_image) forKey:#"picture"];
and change the graph path to "me/photos" instead of "me/feed"
Make these changes, it worked for me.
Remember you need to use "publish_actions" permissions.
"me/photos" is meant for the photo actually be in the "Photo's" list on your Facebook profile. "me/feed" is just a post on the timeline.
After calling the PeoplePicker and selecting an entry from Contacts I can't seem to get the selected contact information to display in my view. Following Apple's Address Book Programming Guide for iOS, I display the People Picker modally and make a selection. Apple's code examples have the information being displayed in UILabels while I, because I also allow the user to manually input information into the text fields in the same view controller, need to have the information displayed in UITextFields. I've proved that the selected data winds up in the target UITextField (which is named "contactName") by printing to the console. The problem is, the selected data is not displayed in the view. When the user inputs manually, there is no problem. I just can't figure out how to transfer the data from the Address Book into the UITextFields in the view controller.
I've been trying for days, but can't resolve this issue. I'm probably overlooking something very basic. I'm new at this, so any help will be appreciated.
- (BOOL)peoplePickerNavigationController:(ABPeoplePickerNavigationController *)peoplePicker shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
// NSString* name = (NSString *)ABRecordCopyValue(person,kABPersonFirstNameProperty);
NSString *name = [NSString stringWithFormat:#"%# %#",ABRecordCopyValue(person,kABPersonFirstNameProperty), ABRecordCopyValue(person,kABPersonLastNameProperty)];
self.contactName.text = name; // 11/17/11
NSLog(#"%#", name);
// [name release]; Commenting out this code prevents the app from freezing when a name is selected from the picker. 11/25/11
NSLog(#"%#",self.contactName.text); // 11/17/11
// 11/16/11 add additional contact info here
[self dismissModalViewControllerAnimated:YES];
return NO;
}
As of iOS 6, [self dismissModalViewControllerAnimated] is deprecated. If you try this, your code will work.
[self dismissViewControllerAnimated:YES completion:^(void) {
NSString *name = [NSString stringWithFormat:#"%#", ABRecordCopyValue(person, kABPersonFirstNameProperty)];
contactName.text=name;
}];
-(IBAction)addToAddressbook:(id)sender{
NSString *fname=#"firstname";
NSString *lname=#"lastname";
NSArray *arrayAdd=[[NSArray alloc]initWithObjects:#"street Name",#"city Name",#"country code",#"zip",nil];
UIImage *image=[UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"ambani.png" ofType:nil]];
[self addContact:fname:lname:arrayAdd:image];
}
-(void) addContact:(NSString *)firstname:(NSString *)lastname:(NSArray *)arrayAddress:(UIImage *)currentImage
{
ABAddressBookRef addressBook=ABAddressBookCreate();
ABRecordRef person=ABPersonCreate();
//set Image
NSData * dataRef = UIImagePNGRepresentation(currentImage);
ABPersonSetImageData(person, (CFDataRef)dataRef, nil);
//set FirstName and LastName
ABRecordSetValue(person, kABPersonFirstNameProperty,firstname, nil);
ABRecordSetValue(person, kABPersonLastNameProperty,lastname, nil);
//Add Address
ABMutableMultiValueRef address=ABMultiValueCreateMutable(kABMultiDictionaryPropertyType);
NSMutableDictionary *addressDictionary=[[NSMutableDictionary alloc]init];
[addressDictionary setObject:[arrayAddress objectAtIndex:0] forKey:(NSString *)kABPersonAddressStreetKey];
[addressDictionary setObject:[arrayAddress objectAtIndex:1]forKey:(NSString *)kABPersonAddressCityKey];
[addressDictionary setObject:[arrayAddress objectAtIndex:2] forKey:(NSString *)kABPersonAddressCountryCodeKey];
[addressDictionary setObject:[arrayAddress objectAtIndex:3] forKey:(NSString *)kABPersonAddressCountryKey];
ABMultiValueAddValueAndLabel(address, addressDictionary, kABHomeLabel, nil);
ABRecordSetValue(person, kABPersonAddressProperty, address, nil);
ABAddressBookAddRecord(addressBook,person, nil);
ABAddressBookSave(addressBook,nil);
objABPersonViewController=[[ABUnknownPersonViewController alloc]init];
objABPersonViewController.displayedPerson=person;
[self.navigationController pushViewController:objABPersonViewController animated:YES];
CFRelease(person);
}
-(void) validateAndDisplayContacts
{
if([firstName length]==0)
{
firstName=#" ";
}
lblName.text=[NSString stringWithFormat:#"%# : %#",#"First Name",name];
[firstName release];
if([mobile length]==0)
{
mobile=#" ";
}
lblPhone.text=[NSString stringWithFormat:#"%# : %#",#"Mobile",mobile];
[mobile release];
if([email length]==0)
{
email=#" ";
}
lblEmail.text=[NSString stringWithFormat:#"%# : %#",#"Email",email];
[email release];
}
- (void)unknownPersonViewController:(ABUnknownPersonViewController *) unknownCardViewController didResolveToPerson:(ABRecordRef)person
{
[objABPersonViewController dismissModalViewControllerAnimated:YES];
}
I need to get the user news feed data.
Currently I'm using this:
[[FBManager defaultManager]getFBRequestWithGraphPath:#"me/home" params: andDelegate:self];
and then:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSArray class]])
result = [result objectAtIndex:0];}
result gives me a bunch of data. But how do Extract these individually? Maybe the name and message for example??
I'd change from using requestWithGraphPath to requestWithMethodName.
Here's the sample code:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
[NSString stringWithFormat:#"SELECT post_id, actor_id, message FROM stream WHERE filter_key = 'others '", #"query",
nil];
[facebook requestWithMethodName: #"fql.query"
andParams: params
andHttpMethod: #"POST"
andDelegate: self];
Then in the request didLoad method:
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
result = [result objectAtIndex:0];
friendID = [[result objectForKey:#"actor_id"]copy];
friendMsg = [[result objectForKey:#"message"]copy];
}
Facebook documentations on the iOS FB Connect SDK are very blend. It helps if you know a bit of SQL(fql) :)
I want to publish a picture with a title (#name) and a texte (#caption) on facebook when my quiz is over.
I try to put my picture in an UIImage then i called her with #picture int the attachment but it doesn't work at all.
Have you a piece of code to show me how i can do this?
Thank you
Flo
This works for me :
- (void) uploadPhoto:(UIImage *) img caption:(NSString *) caption delegate:(NSObject<FBRequestDelegate> *) delegate{
NSMutableDictionary * params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
img, #"picture",
nil];
if (caption != nil) {
[params setObject:params forKey:#"message"];
}
[self requestWithGraphPath:#"me/photos"
andParams:params
andHttpMethod:#"POST"
andDelegate:delegate];
}
I think you have a typo in your method. I believe:
[params setObject:params forKey:#"message"];
should read:
[params setObject: caption forKey:#"message"];