Publish an image with text on facebook - ios

I would like to post a feed on facebook by using fallback share. It should contain an image and a message. I have tried soo much by changing the params
NSMutableDictionary *postParams =
[[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"http://www.abc.com",#"link",
self.produtObj.productImageURL, #"picture",
self.produtObj.productName, #"name",
self.produtObj.productDescription, #"message",
nil];
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters: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];
}];
With this code, the feed is displayed in a box and clicking on it is taking me to the link spcified. I just want to have an image thumbnail with the story for it not inside the box. Please help me. This is my first question in SOF. So please forgive me for my mistakes.
Thanks in advance. :)

I really prefer to use the UIActivityItemViewConroller for pushing stuff up to facebook.
The user needs to be logged into facebook on their device. You can do that through settings in the Facebook section.
I make the new controller like this for my stuff:
NSMutableArray *stuff = [[NSMutableArray alloc]init];
NSString *textstring = #"Now is the time for all good men to come to the aid of their country. Lorum Ipsum etc";
UIImage *pic = [UIImage imageNamed:#"Icon-Small-50"];//A local image
NSString *URL = #"http://nwc.co/images/nwc-icon-200.gif";//A link to an image
[stuff addObject:textstring];
[stuff addObject:pic];
[stuff addObject:URL];
UIActivityViewController *vc = [[UIActivityViewController alloc]initWithActivityItems:stuff applicationActivities:nil];
[self.navigationController presentViewController:vc animated:YES completion:^{
//do something here when they are done
}];
If you run the above, you'll notice that the text, the local image, and a link to the online image all appear on the post.
And you can exclude other activities, if you don't want to confuse people when the activity icons pop up:
vc.excludedActivityTypes = #[UIActivityTypePrint, UIActivityTypePostToTwitter, UIActivityTypePostToWeibo, UIActivityTypeMail, UIActivityTypeCopyToPasteboard, UIActivityTypeAssignToContact, UIActivityTypeSaveToCameraRoll];

Related

UIActivityViewController not showing Message option When Sharing Image Object

I am using UIActivityViewController to share my generated image, it worked fine for certain apps like Whatsapp or sharing via Email, but i also wanted to share it using Messages app. I've tried several ways to do it but i can't display Messages app on it.
Here's my code :
UIImage *receiptStage3 = [CreateReceiptImage putLogo:nil putLabel:TRANSACTION_RECEIPT inImage:receiptStage2];
NSData *imageData = UIImageJPEGRepresentation(receiptStage3,0.5);
// create url
NSDateFormatter *dateFormatter=[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyyMMddHHmmss"];
NSString *fileName = [NSString stringWithFormat:#"%#%#%#", #"FormatHere-", [dateFormatter stringFromDate:[NSDate date]],#".jpg"];
NSURL *url = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingString:fileName]];
NSData *data = imageData;
// write data
[data writeToURL:url atomically:NO];
NSArray *activityItems = #[url];
UIActivityViewController *activityVC = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
activityVC.excludedActivityTypes = #[UIActivityTypePostToTencentWeibo, UIActivityTypePostToVimeo, UIActivityTypePostToWeibo, UIActivityTypePostToFlickr, UIActivityTypePostToTwitter, UIActivityTypePostToFacebook, UIActivityTypePrint, UIActivityTypeAssignToContact, UIActivityTypeOpenInIBooks, UIActivityTypeAirDrop,UIActivityTypeSaveToCameraRoll,UIActivityTypeAddToReadingList];
[activityVC setCompletionWithItemsHandler:^(NSString *activityType, BOOL completed, NSArray *returnedItems, NSError *activityError) {
//Delete file
NSError *errorBlock;
if([[NSFileManager defaultManager] removeItemAtURL:url error:&errorBlock] == NO) {
NSLog(#"error deleting file %#",#"error");
return;
}
}];
[self presentViewController:activityVC animated:YES completion:nil];
As i said before i've tried several ways like putting NSUrl #[url] and UIImage *receiptStage3 directly to initWithActivityItems. I've also tried to remove excludedActivityTypes but the Message option wont show. Am i missing something ? or are there another ways to do this ? Thanks before
Your code is completely fine, works to me.
First of all you Messages app may be missing if you have iMessage disabled in your settings. Go to Settings->Messages and make sure it's on:
Also you may not see it in the default items, check out hidden ones:

Display google navigation based on given locations

I am working on google maps integration I am trying to display google navigation at present I am using the following code. I am trying to display like google navigation based on location what I pass through the api
NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;NSURL *url=[[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%f,%f&destination=%f,%f&alternateroutes=false&sensor=true" ,12.920631,77.670494,8.3075,77.2218]];
NSURLResponse *res;
NSError *err;
NSData *data=[NSURLConnection sendSynchronousRequest:[[NSURLRequest alloc] initWithURL:url] returningResponse:&res error:&err];
if(data)
{
NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
if(dic)
{
NSArray *routes=dic[#"routes"];
NSArray *legs=routes[0][#"legs"];
NSArray *steps=legs[0][#"steps"];
NSLog(#"the legs are:%#",steps);
NSMutableArray *textsteps=[[NSMutableArray alloc] init];
NSMutableArray *latlong=[[NSMutableArray alloc]init];
for(int i=0; i< [steps count]; i++){
NSString *html=steps[i][#"html_instructions"];
[latlong addObject:steps[i][#"end_location"]];
NSLog(#"the data:%#",steps[i][#"end_location"]);
[textsteps addObject:html];
encodedPath = [[[steps objectAtIndex:i] valueForKey:#"polyline"] valueForKey:#"points"];
[self polylineWithEncodedString:encodedPath];
polyline.strokeColor = [UIColor redColor];
polyline.strokeWidth = 2.f;
polyline.map = mapView;
NSLog(#"the encoded patg:%#",encodedPath);
GMSMarker *marker1 = [[GMSMarker alloc]init];
marker1.map = mapView;
NSLog(#"Direction path");
}
}
else
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"" message:#"Connection Error" delegate:self cancelButtonTitle:#"OK" otherButtonTitles:#"", nil];
[alert show];
}
I am expecting an output like
You want to show same direction, time and everything as Google Maps do. Google Maps SDK of iOS will draw a path for you on maps.
You can use the Google Direction API to get and request for direction between source and destination. You can use GMSPolyline to draw it.
But other things, like where to take a turn, whats time is left to reach the destination and other things, you need to manage manually. If you want to show same as Google, you need to make URL and open in WebView.
You can see URLSchema documentation for more detail.
Hoping you are expecting like this code
if ([[UIApplication sharedApplication] canOpenURL:
[NSURL URLWithString:#"comgooglemaps://"]]) {
[[UIApplication sharedApplication] openURL:
[NSURL URLWithString:#"comgooglemaps://?center=40.765819,-73.975866&zoom=14&views=traffic"]];
} else {
NSLog(#"Can't use comgooglemaps://");
}

Sharing video with airdrop

I am having some trouble in sharing videos with airdrop. So, i am using the AssetLibrary like this :
else if (conformsToVideo) {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Asset Loaded" message:#"Video One Loaded"
delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
self.mediaAsset = [AVAsset assetWithURL:[info objectForKey:UIImagePickerControllerMediaURL]];
UIActivityViewController * controller = [[UIActivityViewController alloc] initWithActivityItems:#[self.mediaAsset] applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
Maybe this is just not the way to do it, I don't know and I didn't find any tutorial about it so if you have one, I will gladly take it.
Now my problem is that when i select a video everything works fine until the UIActivityViewController pops out , i don't have any error but I can't use airdrop (nor any other service BTW) the only thing I can do is press the Cancel button of the UIAVController.
I am using iOS 8.3.
Thanks for your help
Ok, eventually I found an answer, maybe not the best but I put it there in case it helps someone cause I didn't find much on sharing video with airdrop :
NSURL * path = [info objectForKey:UIImagePickerControllerReferenceURL];
BOOL conformsToVideo = (UTTypeConformsTo((__bridge_retained CFStringRef) mediaType, kUTTypeAudiovisualContent));
if (conformsToVideo) {
[self.library assetForURL:path
resultBlock:^(ALAsset *asset) {
ALAssetRepresentation* assetRepresentation = [asset defaultRepresentation];
NSString* outputDirectory = [NSString stringWithFormat:#"%#", NSTemporaryDirectory()];
NSString* pathToCopy = [outputDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", assetRepresentation.filename]];
NSUInteger size = (NSUInteger)assetRepresentation.size;
NSMutableData* data = [NSMutableData dataWithLength:size];
NSUInteger bytesRead = [assetRepresentation getBytes:data.mutableBytes fromOffset:0 length:size error:nil];
NSURL * url = nil;
if ([data writeToFile:pathToCopy atomically:YES])
{
NSLog(#"Ok");
url = [NSURL fileURLWithPath:pathToCopy];
UIActivityViewController * controller = [[UIActivityViewController alloc] initWithActivityItems:#[url] applicationActivities:nil];
[self presentViewController:controller animated:YES completion:nil];
}
} failureBlock:^(NSError *error) {
NSLog(#"Failure to use the ALAsset");
}
];
}
I found the solution using this question : Share a video from asset library with AirDrop fails
I am merely adding the previous steps to the code given there, hope it can be useful.

Open Facebook iOS native app WITH back button to my app

I am trying to open facebook app via AppLinks url , it opens user profile/page but does not show button "back to referer app" , I am providing "referer_app_link" data ,
I have generated JSON by this reference http://applinks.org/documentation/#applinknavigationprotocol
NSDictionary *dict = #{
#"target_url" : #"fb://profile/USER_ID",
#"referer_app_link" : #{
#"target_url" : #"MY WEBSITE",
#"url" : #"CALLBACK URL",
#"app_name" : #"MY APP NAME",
#"app_store_id" : #"MY APP STORE ID"
}
};
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:0 error:nil];
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
jsonString = [jsonString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *stringUrl = [NSString stringWithFormat:#"fb://applinks?al_applink_data=%#",jsonString];
NSLog(#"String url is %#",stringUrl);
NSURL *url = [NSURL URLWithString:stringUrl];
if([[UIApplication sharedApplication] canOpenURL:url]) {
[[UIApplication sharedApplication] openURL:url];
} else {
NSLog(#"Cant open %#",url);
}
any ideas ? is Facebook supposed to have "back button" at all ?
my url scheme is set up correctly ...
Update:
NSDictionary contains all valid values , I dont want to publish them at the moment , but url , name , store id ... etc all are valid
Update #2:
Since iOS 9 , this is done by iOS System automatically.
applink is not wired into the FB friend profile page if you simply use the FB Custom URL to link into FB.APP or to safari it will not go back to your app automatically.
The alternative to this is to use the FB IOS SDK and Pick and display the remote user within your app as follows: (code from HelloFacebook sample app (comes with the SDK)
- (IBAction)pickFriendsClick:(UIButton *)sender {
FBFriendPickerViewController *friendPickerController = [[FBFriendPickerViewController alloc] init];
friendPickerController.title = #"Pick Friends";
[friendPickerController loadData];
// Use the modal wrapper method to display the picker.
[friendPickerController presentModallyFromViewController:self animated:YES handler:
^(FBViewController *innerSender, BOOL donePressed) {
if (!donePressed) {
return;
}
NSString *message;
if (friendPickerController.selection.count == 0) {
message = #"<No Friends Selected>";
} else {
NSMutableString *text = [[NSMutableString alloc] init];
// we pick up the users from the selection, and create a string that we use to update the text view
// at the bottom of the display; note that self.selection is a property inherited from our base class
for (id<FBGraphUser> user in friendPickerController.selection) {
if ([text length]) {
[text appendString:#", "];
}
[text appendString:user.name];
}
message = text;
}
[[[UIAlertView alloc] initWithTitle:#"You Picked:"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil]
show];
}];
}
Note - the sample currently just picked the name property from the FBGraphUser Class instance ....
user will have other properties birthday, sex etc, just lookup header file within the SDK or look up FB documentation.

How do I customize a UIActivityViewController to show a URL link when posting to facebook and twitter?

So I'm trying out the new UIActivityViewController in iOS 6, and it's really easy to get up and running, but I can't figure out how to control it like I want. So I want to post a link to an article and I also want to attach an image for the link. I DON'T want that image uploaded to some facebook album, just as a URL thumbnail.
This is easy to accomplish in the facebook SDK as they give full control for it, but is there a way to do it with the UIActivityViewController? Here's what I got:
NSArray *activityItems = #[[NSURL URLWithString:[article link]], [UIImage imageNamed:#"myStockImage"]];
UIActivityViewController *viewCont = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:nil];
[self presentViewController:viewCont animated:YES completion:nil];
And this works, but it uploads the image to an 'iOS album'. If I don't add the image in the array, then the facebook sheet looks like it's blank and the attachment shows a grayed out safari logo (like the thumbnail is missing!) In safari when you try to Facebook a link, it uses a screen grab of the page as the thumbnail, I want to do something like that
UPDATE :
So here's what it looks like from my app (using UIActivityViewController or the SLCompose way). See how it is going to upload the picture to a photo album iOS Photos
Here's what I want it to look like (see Safari also) :
I've searched about this and I've come to the conclusion that using the UIActivityViewController there's just no way to do what you intend to. Every time you try to share a photo it just makes you put the photo in one of your albums, "iOS" album by default.
In my case, I did not need to post a photo as long as an image was retrieved from the link I needed to share (just like when you post a link on your Facebook timeline and it automatically grabs a picture from that link, and the picture becomes the link). In order to do that, I figured out that if I posted only an URL it does not work. You have to post some initial text and then the URL, and you do so by putting the objects in that order within the activityItems array.
This is my working code:
NSArray * activityItems = #[[NSString stringWithFormat:#"Some initial text."], [NSURL URLWithString:#"http://www.google.com"]];
NSArray * applicationActivities = nil;
NSArray * excludeActivities = #[UIActivityTypeAssignToContact, UIActivityTypeCopyToPasteboard, UIActivityTypePostToWeibo, UIActivityTypePrint, UIActivityTypeMessage];
UIActivityViewController * activityController = [[UIActivityViewController alloc] initWithActivityItems:activityItems applicationActivities:applicationActivities];
activityController.excludedActivityTypes = excludeActivities;
[self presentViewController:activityController animated:YES completion:nil];
I also noticed that if you post a photo along these objects, it will not retrieve any image from the link.
I hope this helps.
Updated the answer for Swift 3.0
let url = URL(string: "google.com")
let shareText = "Your string goes here"
let shareItems: [Any] = [shareText, url!]
let activityVC = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
activityVC.excludedActivityTypes = [.airDrop, .postToFlickr, .assignToContact, .openInIBooks]
self.present(activityVC, animated: true, completion: nil)
Facebook won't accept the string, but, like many other of the social media sites, will show an image/link box for the URL
If you don't specifically need to use UIActivityViewController using SLComposeViewController is easy to use for this purpose.
+(void)presentShareWidgetWithText:(NSString*)text url:(NSURL*)url images:(NSArray*)images toService:(NSString*)service presentIn:(UIViewController*)parentViewController {
SLComposeViewController* controller = [SLComposeViewController composeViewControllerForServiceType:service];
if (controller == nil) {
DLog(#"Could not initialize SLComposeViewController for %#!", service);
return;
}
if (url != nil) {
if (![controller addURL:url])
DLog(#"Failed adding url %#!", url);
}
if (images != nil) {
for (UIImage* image in images) {
if (![controller addImage:image]) {
DLog(#"Failed adding image: %#", image);
}
}
}
if (![controller setInitialText:text]) {
DLog(#"Failed setting initial text: %#", text);
}
SLComposeViewControllerCompletionHandler handler = ^(SLComposeViewControllerResult result) {
switch (result) {
case SLComposeViewControllerResultCancelled:
DLog(#"SLComposeViewControllerResultCancelled");
break;
case SLComposeViewControllerResultDone:
DLog(#"SLComposeViewControllerResultDone, Shared on service: %#", service);
break;
default:
DLog(#"Unhandled result: %d", result);
break;
}
dispatch_async(dispatch_get_main_queue(), ^{
[parentViewController dismissViewControllerAnimated:YES completion:^{
DLog(#"Dismissed a controller here!");
}];
});
};
[controller setCompletionHandler:handler];
[parentViewController presentViewController:controller animated:YES completion:^{
DLog(#"Presented %#!", controller);
}];
}
- (void)tweetURL:(NSString *)url title:(NSString *)title {
TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];
NSString *format = #"“%#” %# /via #DesignSceneApp";
NSString *message = [NSString stringWithFormat:format, title, url]
NSUInteger idx = title.length;
while (![twitter setInitialText:message]) {
idx -= 5;
if (idx > 5) {
message = [NSString stringWithFormat:format,
[NSString stringWithFormat:#"%#…", [title substringToIndex:idx]],
url
];
} else {
// Give up on the title.
message = [NSString stringWithFormat:#"%# /via #DesignSceneApp", url];
[twitter setInitialText:message];
break;
}
}
[self presentViewController:twitter animated:YES completion:nil];
}

Resources