I created a code swift, that use facebook SDK 4.x. The code use FBSDKShareButton and worked very well.
This is the code:
let content : FBSDKShareLinkContent = FBSDKShareLinkContent()
content.contentURL = NSURL(string: "http://alexandreccarmo.com")
content.contentTitle = "Teste"
content.contentDescription = "teste teste"
content.imageURL = NSURL(string: "xxxx/2.jpg")
let button : FBSDKShareButton = FBSDKShareButton()
button.shareContent = content
button.frame = CGRectMake((UIScreen.mainScreen().bounds.width - 100) * 0.5, 50, 100, 25)
self.view.addSubview(button)
But I need to share without use facebook dialog. When the user click on button of my app I need share directly on their facebook.
I tried this:
let contentx : FBSDKShareLinkContent = FBSDKShareLinkContent()
contentx.contentURL = NSURL(string: "http://alexandreccarmo.com")
contentx.contentTitle = "Testexxxxx"
contentx.contentDescription = "teste testexxx"
contentx.imageURL = NSURL(string: "xxxx/2.jpg")
FBSDKShareAPI.shareWithContent(contentx, delegate: nil)
But I receive this error:
FacebookLogin[6721:3464359] FBSDKLog: Warning: [FBSDKAccessToken currentAccessToken] is missing publish_actions permissions
I read on facebook developers that I need to request "publish_actions" when I need to send share. But I don't understand how can i do this. Somebody knows?
So here is some code that I used to publish an image on Facebook without the Facebook SDK:
func actionTapped(sender: AnyObject) {
let objectsToShare = //reference to image
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
activityVC.completionWithItemsHandler = actionCompleted
presentViewController(activityVC, animated: true, completion: nil)
}
func actionCompleted(activityType: String!, completed: Bool, returnedItems: [AnyObject]!, error: NSError!) {
// Return if cancelled
if (!completed) {
return
}
close()
}
You can check out these links as well:
Can I use UIActivityViewController to share on Facebook ?
http://roadfiresoftware.com/2014/02/how-to-add-facebook-and-twitter-sharing-to-an-ios-app/
UIActivityViewController share only text
I hope this helps.
Related
I'm trying to share my app using UIActivityViewController but I can't reproduce the same effect as when I share an app from the App Store, meaning :
When I clicked the share button in the App Store I have something that looks like this :
But when I try to share my app I have this :
The code that I used was :
if let logo = UIImage(named: "myLogo"), let websiteURL = URL(string: "https://itunes.apple.com/app/idxxxxxxxxxx") {
let objectsToShare = ["My App Name", websiteURL, logo] as [Any]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: [])
if let popoverController = activityVC.popoverPresentationController {
popoverController.sourceView = self.view
popoverController.permittedArrowDirections = UIPopoverArrowDirection(rawValue: 0)
}
present(activityVC, animated: true)
}
The if let popoverController = ... loop is for preventing a crash when using iPads.
What do I have to change in order to have the effect as the App Store? (to have an image with a title and a subtitle)
Moreover, once I share the app with Messages for instance, this is the difference :
How can I have the same effect? (A single image with the title and subtitle, an as a bonus, a video). I'm not sure if this is an iOS 13 problem, since all similar questions don't have the same app sharing popover.
You have to use the new LinkPresentation framework.
Which essentially involves UIActivityItemSource conformance then retrieving the metadata that will encompass the Activity View and the data you are sharing. Data can be retrieved locally or downloaded.
ExampleController: UIViewController {
var metadata: LPLinkMetadata?
func share() {
let activityView = UIActivityViewController(activityItems: [self], applicationActivities: nil)
present(activityView, animated: true)
}
...
}
extension ExampleController: UIActivityItemSource {
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return metadata
}
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
return metadata
}
func activityViewControllerLinkMetadata(_: UIActivityViewController) -> LPLinkMetadata? {
metadata = LPLinkMetadata()
metadata.title = "Title"
metadata.originalURL = URL(string: "Description")
metadata.url = metadata.originalURL
// Using a locally stored item
metadata.iconProvider = NSItemProvider(object: UIImage(named: "image")!)
metadata.imageProvider = NSItemProvider.init(contentsOf:
Bundle.main.url(forResource: "image", withExtension: "JPG"))
return metadata
}
}
Docs:
https://developer.apple.com/documentation/uikit/uiactivityitemsource/3144571-activityviewcontrollerlinkmetada
WWDC Presentation:
https://developer.apple.com/videos/play/wwdc2019/262/
activityViewController.popoverPresentationController?.sourceView = self.view // so that iPads won't crash
You can use this.
I want to share an HTML link on facebook without install SDK like WhatsApp or twitter. I am using below code for share a link on facebook. But I want to share the post to direct app without an open safari browser.
Please tell me this is possible or not.I have searched alot but not find any solution.
//For share twitter
let urlWhats = "twitter://post?message=\(fileURL)"
let urlString = urlWhats.addingPercentEncoding(withAllowedCharacters: NSCharacterSet.urlQueryAllowed)
let whatsappURL = URL(string: urlString!)
if UIApplication.shared.canOpenURL(whatsappURL!)
{
UIApplication.shared.open(whatsappURL!, options: [:], completionHandler: nil)
}
//For Facebook
let shareURL = "https://www.facebook.com/sharer/sharer.php?u=" + url
if let url = URL(string:shareURL)
{
let vc = SFSafariViewController(url: url, entersReaderIfAvailable: true)
vc.delegate=self
present(vc, animated: true)
}
Thanks in Advance
For sharing in FB make use of 'FacebookShare'
import FBSDKShareKit
class yourViewController: UIViewController {
func shareContentInFB() {
let content = FBSDKShareLinkContent()
content.contentURL = URL(string: "http://yourURL/")
content.quote = "Hey !!!!"
let dialog : FBSDKShareDialog = FBSDKShareDialog()
dialog.fromViewController = self
dialog.shareContent = content
dialog.mode = FBSDKShareDialogMode.automatic
dialog.show()
}
}
You cannot prefill text in fb using this, if you have to do it then make use of Fb graph API
I am trying to share an image with description to the facebook from my app using FBSDKShareKit. but the problem is, I am unable to add description with the image .
Currently I have:
let content: FBSDKSharePhotoContent = FBSDKSharePhotoContent()
let photo:FBSDKSharePhoto = FBSDKSharePhoto()
photo.image = imageView.image
photo.isUserGenerated = true
content.photos = [photo]
content.contentURL = URL(string:directUrl)
FBSDKShareDialog.show(from: self, with: content, delegate: nil)
I also have tried:
let vc = SLComposeViewController(forServiceType:SLServiceTypeFacebook)
vc?.add(imageview.image)
vc?.add(URL(string: "http://www.example.com/"))
vc?.setInitialText("description")
self.present(vc!, animated: true, completion: nil)
using social ,In which setInitialText does not work according to this answer
I tried this too:
Is there any other way in which I can share image with description to fb?
My app is not Live yet. I got the app ID from the App Store Connect. I want to share the app link on social media apps. I used the UIActivityViewController:
let string1 = "itms-apps://itunes.apple.com/app/idXXXXXXX"
let url = NSURL(string: string1)
let shareItems = [UIApplication.sharedApplication().openURL(url!)]
let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
self.presentViewController(activityViewController, animated: true, completion: nil)
Problem: It is not showing some social media apps like WhatsApp.
Solution for Swift 4 or better:
This solution also works on iPad (the solution above crashes on iPad):
if let urlStr = NSURL(string: "https://apps.apple.com/us/app/idxxxxxxxx?ls=1&mt=8") {
let objectsToShare = [urlStr]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
if UIDevice.current.userInterfaceIdiom == .pad {
if let popup = activityVC.popoverPresentationController {
popup.sourceView = self.view
popup.sourceRect = CGRect(x: self.view.frame.size.width / 2, y: self.view.frame.size.height / 4, width: 0, height: 0)
}
}
self.present(activityVC, animated: true, completion: nil)
}
This is used to open the site, not to share the app:
[UIApplication.sharedApplication().openURL(url!)]
Do this instead:
if let name = URL(string: "https://itunes.apple.com/us/app/myapp/idxxxxxxxx?ls=1&mt=8"), !name.absoluteString.isEmpty {
let objectsToShare = [name]
let activityVC = UIActivityViewController(activityItems: objectsToShare, applicationActivities: nil)
self.present(activityVC, animated: true, completion: nil)
} else {
// show alert for not available
}
for sample see this
The solutions here are all good but it's worth considering implementing the UIActivityItemSource protocol and LinkPresentation framework.
My solution achieves the following:
App icon and title showing at the top of the UIActivityViewController
Direct link to App Store for AirDrop ActivityType
Custom text for messages and emails, including an opportunity to add a link to the app on Google Play if required
Subject for emails
Doesn't use the LPMetaDataProvider fetch request (as described in this WWDC 2019 262 video) so faster to load
0. Init the UIActivityViewController:
Set the items to self:
let activityVC = UIActivityViewController(activityItems: [self], applicationActivities: nil)
Exclude certain ActivityTypes which don't apply:
activityVC.excludedActivityTypes = [.addToReadingList, .assignToContact, .markupAsPDF, .openInIBooks, .saveToCameraRoll]
For iPad set the popoverPresentationController.sourceView or .barButtonItem (this is ignored on iPhone):
activityVC.popoverPresentationController?.sourceView = myButton
Present it:
present(activityVC, animated: true, completion: nil)
1. Implement the required UIActivityItemSource methods
https://developer.apple.com/documentation/uikit/uiactivityitemsource
You must implement the placeholder method which according to the docs:
Placeholder objects do not have to contain any real data but should be configured as closely as possible to the actual data object you intend to provide.
func activityViewControllerPlaceholderItem(_ activityViewController: UIActivityViewController) -> Any {
return ""
}
And the actual data, returning a link to the app for AirDrop and text for everything else:
func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
if activityType == .airDrop {
return URL(string: "APP_STORE_URL")!
}
return "Check out the APP_NAME on the App Store: APP_STORE_URL or on the Google Play Store: PLAY_STORE_URL"
}
2. Implement the subject method
From the docs:
For activities that support a subject field, returns the subject for the item.
func activityViewController(_ activityViewController: UIActivityViewController, subjectForActivityType activityType: UIActivity.ActivityType?) -> String {
return "EMAIL_SUBJECT" // e.g. App name
}
3. Implement the LPLinkMetaData method
From the docs:
Returns metadata to display in the preview header of the share sheet.
#available(iOS 13.0, *)
func activityViewControllerLinkMetadata(_ activityViewController: UIActivityViewController) -> LPLinkMetadata? {
let metadata = LPLinkMetadata()
metadata.title = "APP_NAME"
return metadata
}
iPhone solution for Swift 5+
let url = URL(string: "https://apps.apple.com/us/app/id1535629801")!
let vc = UIActivityViewController(activityItems: [url], applicationActivities: nil)
present(vc, animated: true)
I'm trying to post a photo to Facebook, and it works fine using the following code:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [NSObject : AnyObject]) {
self.selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
var photo = FBSDKSharePhoto()
photo.image = self.selectedImage
photo.userGenerated = true
var content = FBSDKSharePhotoContent()
content.photos = [photo]
self.dismissViewControllerAnimated(true, completion: nil)
shareDialog.fromViewController = self
shareDialog.shareContent = content
shareDialog.show()
}
However, this only works when the user has the facebook app downloaded. otherwise it does NOT open the web browser to share the photo, even though facebook state:
The Share Dialog switches to the native Facebook for iOS app, then
returns control to your app after a post is published. If someone
doesn't have Facebook app installed it will automatically falls back
to a web-based dialog.
Any suggestions please ? answers appreciated, thank you.
You can try this:
func postToFacebook(image: UIImage!) {
var SocialMedia :SLComposeViewController = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
SocialMedia.completionHandler = {
result -> Void in
var getResult = result as SLComposeViewControllerResult;
switch(getResult.rawValue) {
case SLComposeViewControllerResult.Cancelled.rawValue: println("Cancelled")
case SLComposeViewControllerResult.Done.rawValue: println("It's Work!")
default: println("Error!")
}
self.dismissViewControllerAnimated(true, completion: nil)
}
self.presentViewController(SocialMedia, animated: true, completion: nil)
SocialMedia.setInitialText("...")
SocialMedia.addImage(image)
}