ios - Swift:截取 viewController 的屏幕截图并在 Facebook 上分享

标签 ios swift facebook swift3

我创建了以下函数来在 Facebook 上分享帖子:

@IBAction func socialShare(_ sender: Any){
    //Alert
    let alert = UIAlertController(title: "Share", message: "First share!", preferredStyle: .actionSheet)

    //First action
    let actionOne = UIAlertAction(title: "Share on Facebook", style: .default) { (action) in

        //Checking if user is connected to Facebook
        if SLComposeViewController.isAvailable(forServiceType: SLServiceTypeFacebook)
        {
            let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
            post.setInitialText("First")
            post.add(UIImage(named: "Mylogo.png"))
            self.present(post, animated: true, completion: nil)
        } else {self.showAlert(service: "Facebook")}
    }

    let actionThree = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
    //Add action to action sheet
    alert.addAction(actionOne)
    alert.addAction(actionThree)

    //Present alert
    self.present(alert, animated: true, completion: nil)    
}

func showAlert(service:String){
    let alert = UIAlertController(title: "Error", message: "You are not connected to \(service)", preferredStyle: .alert)
    let action = UIAlertAction(title: "Dismiss", style: .cancel, handler: nil)

    alert.addAction(action)
    present(alert, animated: true, completion: nil)
}

但我真正想做的是共享图像,并且该图像必须是用户点击共享按钮的 viewController 的屏幕截图。这可能吗?如果是这样,怎么办?

更新:

对于屏幕截图,我找到了这样的函数:

func screenShotMethod() {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.renderInContext(UIGraphicsGetCurrentContext())
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    //Save it to the camera roll
    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil)
}

但我不知道如何在我的代码中实现它。

最佳答案

要做到这一点,你可以这样做

func screenShotMethod() -> UIImage? {
    //Create the UIImage
    UIGraphicsBeginImageContext(view.frame.size)
    view.layer.render(in: UIGraphicsGetCurrentContext()!)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image
}

并将其添加到:

    let post = SLComposeViewController(forServiceType: SLServiceTypeFacebook)!
    post.setInitialText("First")
    post.add(screenShotMethod())
    self.present(post, animated: true, completion: nil)

关于ios - Swift:截取 viewController 的屏幕截图并在 Facebook 上分享,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47352380/

相关文章:

ios - 使用 swiftyjson 从索引对象数组 ios 的 json 中检索标题

ios - 在 tapGesture Action 选择器中包含协议(protocol)功能 - iOS Swift

ios - swift 中的字典值作为字符串(而不是 NSString)

ios - 你知道这个堆栈跟踪意味着什么吗?

ios - 将两个字符串转换为 NSDate

ios - 条件绑定(bind)的初始化程序必须具有可选类型,而不是 CLPlacemark

ios - 如何在 Swift 中替换 Material 中的后退按钮

ios - 我可以在 native iOS 应用程序和后端之间共享 Facebook 身份验证吗?

android - 通过具有自动解析功能的 Android 应用程序在 Facebook 上分享链接

reactjs - 使用jestjs进行单元测试时如何获取组件的props