【问题标题】:Swift: Take a screenshot of the viewController and share it on FacebookSwift:截取 viewController 并在 Facebook 上分享
【发布时间】:2017-11-17 14:01:40
【问题描述】:

我创建了以下功能来在 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)
}

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

【问题讨论】:

  • 也许你应该更好地描述一下你的问题是什么。第二段代码是在“image”变量中创建 UIImage。你只需要使用它而不是“UIImage(命名:“Mylogo.png”)”。但我不确定这是你想要的。

标签: ios swift facebook swift3


【解决方案1】:

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

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)

【讨论】:

  • screenShotMethod() 返回一个可选图像,最好使用 guard 或者 if let
  • 当然!但是 post.add 方法接受可选值,不是吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-21
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 2017-01-26
相关资源
最近更新 更多