Swift崩溃在使用UIDocumentInteractionController时点击"在Instagram中打开"

ash*_*yla 15 share release retain instagram swift

我有以下代码在我的Swift应用程序上分享Instagram上的图像:@IBAction func instagramShareButton(sender:AnyObject){

    let documentsDirectory = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
    let path = documentsDirectory.stringByAppendingPathComponent("Share Icon.igo")

    let imageName: String = "Share Icon.png"
    let image = UIImage(named: imageName)
    let data = UIImagePNGRepresentation(image!)

    data!.writeToFile(path, atomically: true)

    let imagePath = documentsDirectory.stringByAppendingPathComponent("Share Icon.igo")
    let rect = CGRectMake(0, 0, 0, 0)

    UIGraphicsBeginImageContextWithOptions(self.view.bounds.size, self.view.opaque, 0.0)
    self.view.layer.renderInContext(UIGraphicsGetCurrentContext()!)
    UIGraphicsEndImageContext()

    let fileURL = NSURL(fileURLWithPath: imagePath)
    print("fileURL = \(fileURL)")

    var interactionController = UIDocumentInteractionController(URL: fileURL)

    interactionController.delegate = self

    interactionController.UTI = "com.instagram.exclusivegram"

    let msgBody = "My message"
    interactionController.annotation = NSDictionary(object: msgBody, forKey: "InstagramCaption")
    interactionController.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

func documentInteractionControllerWillPresentOpenInMenu(controller:UIDocumentInteractionController){}

代码由Objective C翻译成Swift,因为我没有在Swift中找到任何可以在Instagram上分享的内容.

菜单弹出,我在那里看到Instagram,当我点击它时,我收到以下错误:

断言失败 - [_ UIOpenWithAppActivity performActivity],/ BuildRoot/Library/Cache/com.apple.xbs/Source/UIKit/UIKit-3505.16/UIDocumentInteractionController.m:408

***由于未捕获的异常'NSInternalInconsistencyException'而终止应用程序,原因是:'UIDocumentInteractionController过早地消失了!'

我相信我不得不释放UIDocumentInteractionController对象.我对吗?没有找到任何信息来帮助我理解我如何在Swift中做到这一点.请帮我弄清楚如何解决这个问题.

Fer*_*iss 43

我认为你是对的.我也有同样的问题.

在开始共享功能之前,必须从UIDocumentInteractionController创建一个全局变量:

var interactionController: UIDocumentInteractionController?
@IBAction func instagramShareButton(sender: AnyObject) {
    ...
    interactionController = UIDocumentInteractionController(URL: fileURL)
    interactionController!.UTI = "com.instagram.exclusivegram"
    let msgBody = "My message"
    interactionController!.annotation = NSDictionary(object: msgBody, forKey: "InstagramCaption")
    interactionController!.presentOpenInMenuFromRect(rect, inView: self.view, animated: true)
}
Run Code Online (Sandbox Code Playgroud)

这适合我!

  • 发生这种情况是因为当用户选择控制器中任何已启用的应用程序时,需要使用`UIDocumentInteractionController`实例.它崩溃了,因为当用户点击应用程序时控制器被释放.我们需要全局变量来保持文档控制器的活跃性.请注意,仅导出到AirDrop时,不使用文档控制器,它可以是局部变量. (2认同)
  • 全局表示全局类变量btw,或多或少在上面的代码中显示. (2认同)