2

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
    }
5
  • for an Alternative you can use webview also Commented May 8, 2017 at 13:31
  • "The application breaks": Can you post a log message? How does it "break"? Commented May 8, 2017 at 13:33
  • @vivek I need to export my archives Commented May 8, 2017 at 13:35
  • save files to document folders and then load file to webview locally from document folder. Commented May 8, 2017 at 13:42
  • @paper1111 I edit the post with more info about this! Commented May 8, 2017 at 13:47

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1
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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.