如何在 swift 中同时分享图片和文字?

How to share both Image and Text together in swift?

我正在尝试在 swift 中共享图像和文本。但是当我选择通过 facebook、messenger 或 whatsapp 分享时,它只提供文字(不分享图片)。我正在使用 UIActivityViewController 进行分享。

这是我的代码:

func displayShareSheet(latitude:NSString?, longitude:NSString?, image:UIImage?, address:NSString? ) {
    let activityViewController = UIActivityViewController(activityItems: [(latitude as NSString?)!, (longitude as NSString?)!, (image as UIImage?)!, (address as NSString?)!], applicationActivities: nil)
    presentViewController(activityViewController, animated: true, completion: {}
)
}

试试这个对我有用!!!

@IBAction func btnExport(sender: AnyObject)
{

    print("Export")
    let someText:String = "Hello want to share text also"
    let objectsToShare:UIImage = self.imgView.image!
    let sharedObjects:[AnyObject] = [objectsToShare,someText]
    let activityViewController = UIActivityViewController(activityItems : sharedObjects, applicationActivities: nil)
    activityViewController.popoverPresentationController?.sourceView = self.view

    activityViewController.excludedActivityTypes = [ UIActivityTypeAirDrop, UIActivityTypePostToFacebook,UIActivityTypePostToTwitter]

    self.presentViewController(activityViewController, animated: true, completion: nil)
}

下面的 UIActivityViewController 代码对我有用。还附上了这两种方法的屏幕截图。

 func shareImage() {
            let img = UIImage(named: "SoSampleImage")
            let messageStr = "Ketan SO"
            let activityViewController:UIActivityViewController = UIActivityViewController(activityItems:  [img!, messageStr], applicationActivities: nil)
            activityViewController.excludedActivityTypes = [UIActivityTypePrint, UIActivityTypePostToWeibo, UIActivityTypeCopyToPasteboard, UIActivityTypeAddToReadingList, UIActivityTypePostToVimeo]
            self.presentViewController(activityViewController, animated: true, completion: nil)
        }

UIActivityViewController 示例的屏幕截图:

使用 SLComposeViewController 的替代方法:

func share(){
        let img = UIImage(named: "SoSampleImage")
        let composeSheet = SLComposeViewController(forServiceType: SLServiceTypeFacebook)
        composeSheet.setInitialText("Hello, Ketan!")
        composeSheet.addImage(img)
        self.presentViewController(composeSheet, animated: true, completion: nil)
    }

SLComposeViewController 示例的屏幕截图:

希望对你有所帮助..

如果您有任何疑问,请告诉我。

我在 VisualActivityViewController 的帮助下实现了这一点,它存在于 this GitHub repository

它也为我提供了一个漂亮的自定义视图——向用户显示用户将要共享的文本和图像。