UIDocumentInteractionController not working

吃可爱长大的小学妹 提交于 2019-12-10 22:49:56

问题


In my application I want to download various types of files and exports so that the user can open the file with the application that opens this type of file. I'm trying to use the UIDocumentInteractionController but after downloading save it to my device and trying to open it several problems happen. With .docx the application breaks and with other files it does not appear to encode the file. What can I be doing wrong?

When I try to share the file through the airdrop I get an error that says the file is invalid.

When I share with iBooks I get the message '' NSInternalInconsistencyException ', reason:' UIDocumentInteractionController has gone away prematurely! " And the app breaks

This is my code:

func loadArchiveAtIndex(sender: NSNotification){
        let itemIndex = sender.userInfo!["index"] as! Int
        let archiveKey = sender.userInfo!["downloadKey"] as! String

        self.downloadingItens.append(itemIndex)
            SQLiteDataController().getTokenSincronismo({
                (Valido, Retorno, Token, Tipo) -> Void in
                if Valido == true{
                    switch Retorno {
                    case 9: // Retorno Válido

                        let params = [
                            "tokenSincronizacao":"\(Token)",
                            "chaveProdutoBiblioteca":"\(archiveKey)"
                        ]
                        Alamofire.request(.GET, "\(_URLPREFIX)/WSMhobErpServico/api/sincronizar/ProdutoBiblioteca/ObtemProdutoBiblioteca", parameters: params).responseJSON { (response) in
                            if response.result.isFailure {
                                print(response.result.error)
                            } else {
                                let result = response.result.value
                                if let archive = result?["ProdutoBiblioteca"] as? NSDictionary{
                                    let bytes = archive.objectForKey("Arquivo") as! String
                                    let name = archive.objectForKey("NomeArquivo") as! String
                                    let data = NSData.init(base64EncodedString: bytes, options: .IgnoreUnknownCharacters)
                                    let url = NSURL.init(string: name.lowercaseString)
                                    data?.writeToURL(url!, atomically: true)

                                    let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
                                    let fileURL = documents.URLByAppendingPathComponent((name.lowercaseString))

                                    let dic = UIDocumentInteractionController.init(URL: fileURL!)
                                    dic.delegate = self
                                    dic.presentOpenInMenuFromRect(CGRect.init(x: 0, y: 0, width: 200, height: 200), inView: self.view, animated: true)

                                    var arrayIndex = 0
                                    for item in self.downloadingItens {
                                        let i = item
                                        if i == itemIndex {
                                            self.downloadingItens.removeAtIndex(arrayIndex)
                                            NSNotificationCenter.defaultCenter().postNotificationName("reloadTable", object: nil, userInfo: ["itens":self.downloadingItens])
                                            break
                                        }
                                        arrayIndex = arrayIndex + 1
                                    }
                                } else {
                                    print("erro")
                                }
                            }
                        }

                        break
                    default:
                        self.showError("Atenção", message: "Não foi Possivel Processar a sua Solicitação")
                        break
                    }
                }else{
                    self.showError("Atenção", message: "Não foi Possivel Processar a sua Solicitação")
                }
                }, sincFull:true)
    }

    func documentInteractionControllerViewForPreview(controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }

    func documentInteractionControllerRectForPreview(controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }

    func documentInteractionControllerViewControllerForPreview(controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }

回答1:


Okay I got your point.

I have reviewed your code and I think the problem is in below line

 let dic = UIDocumentInteractionController.init(URL: fileURL!)
 dic.delegate = self

You are creating object of UIDocumentInteractionController inside block so when block will be out of memory or deallocated your UIDocumentInteractionController object will also be released.

So make UIDocumentInteractionController object global. Declare object globally for that class and then assign value inside the block.




回答2:


let name = archive.objectForKey("NomeArquivo") as! String
                                    let data = NSData.init(base64EncodedString: bytes, options: .IgnoreUnknownCharacters)
                                    let documents = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: false)
                                    let fileURL = documents.URLByAppendingPathComponent((name.lowercaseString))
                                    data?.writeToURL(fileURL!, atomically: true)


来源:https://stackoverflow.com/questions/43848833/uidocumentinteractioncontroller-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!