如何在swift中共享图像和文本?

时间:2016-09-22 07:03:53

标签: swift swift2 uiactivityviewcontroller

我试图在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: {}
)
}

3 个答案:

答案 0 :(得分:5)

以下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示例的屏幕截图:

enter image description here

替代使用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示例的屏幕截图:

enter image description here

希望它会帮助你..

如果您有任何疑问,请与我们联系。

答案 1 :(得分:0)

试试这个对我有用!!!

@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)
}

答案 2 :(得分:0)

我借助this GitHub repository中的VisualActivityViewController来实现这一目标

它也为我提供了一个不错的自定义视图,该视图向用户显示了用户要共享的文本和图像。