使用 UIActivityViewController 共享图像

Sharing image using UIActivityViewController

使用 UIActivityViewController 分享来自 UIImageView 的图像?

我正在尝试使用 UIActivityViewController 分享图片,但出现错误:

func shareIMG(){
    let activityItems = [self.imageView.image]
    let avc = UIActivityViewController(activityItems: activityItems, applicationActivities: nil)

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

错误信息:

Cannot find an initializer for type 'UIActivityViewController' that accepts an argument list of type '(activityItems: [UIImage?], applicationActivities: nil)'

有什么想法吗?

您似乎需要使用 !

来解包 activityItems
let activityItem: [AnyObject] = [self.imageView.image as! AnyObject]

let avc = UIActivityViewController(activityItems: activityItem as [AnyObject], applicationActivities: nil)

self.presentViewController(avc, animated: true, completion: nil)

注意:以上代码在Xcode6.3模拟器

中测试

只需创建一个按钮及其操作即可。并像这样安装按钮的动作。

注意:您必须通过设置登录您的 facebook 或 twitter。那就这样吧

@IBAction func onShareTouched(sender: AnyObject) {

    print("share")

    let myShare = "My beautiful photo! <3 <3"
    let image: UIImage = UIImage(named: "yourImageNameHere")

    let shareVC: UIActivityViewController = UIActivityViewController(activityItems: [(image), myShare], applicationActivities: nil)
    self.presentViewController(shareVC, animated: true, completion: nil)

}

使用 Swift 5

   let img  = imageView.image!.pngData()
   let messageStr:String  = "some sharing text"
   let shareItems:Array = [img!, messageStr] as [Any]

   let activityViewController = UIActivityViewController(activityItems: shareItems, applicationActivities: nil)
    activityViewController.excludedActivityTypes = [UIActivity.ActivityType.print, UIActivity.ActivityType.postToWeibo, UIActivity.ActivityType.copyToPasteboard, UIActivity.ActivityType.addToReadingList, UIActivity.ActivityType.postToVimeo]

    if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.phone {
        self.present(activityViewController, animated: true, completion: nil)
        } else {
            let popup: UIPopoverController = UIPopoverController(contentViewController: activityViewController)
            popup.present(from: sender.bounds, in: sender, permittedArrowDirections: UIPopoverArrowDirection.any, animated: true)
        }

使用 Swift 5

注意:将图像作为数据共享时

func shareApplication() {
    
    let description = "Hi, I have shared my profile"
    
    let url = URL(string: "https://cdn.vox-cdn.com/thumbor/9iH_CxCOzkVQACme6xpCkgzydzo=/0x0:1323x638/920x613/filters:focal(539x248:749x458):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/69851120/Screenshot_2021_09_10_7.38.39_AM.0.png")
    
    if let imageData = NSData(contentsOf: url!) {
        
        // MARK: - URL to Data

        let image = UIImage(data: imageData as Data)
        
        let activityVC = UIActivityViewController(activityItems: [description, image ?? UIImage()], applicationActivities: nil)
        self.present(activityVC, animated: true, completion: nil)
    }
}