Jannik Arndt
Jannik Arndt

Reputation: 555

Export file from iOS app in swift

I'm fairly new to Swift and iOS development in general. My app has a model that can easily be expressed as comma separated values (csv), so naturally I want the user to be able to export the data as an csv file and opening that file in another application. Since I didn't find any examples in Swift, I gave it a try on my own:

func ExportToCSV(delegate: UIDocumentInteractionControllerDelegate){
    let fileName = NSTemporaryDirectory().stringByAppendingPathComponent("myFile.csv")
    let url: NSURL! = NSURL(fileURLWithPath: fileName)

    var data  = "Date,Time,Count\n2014-11-21,14.00,42"

    data.writeToURL(url, atomically: true, encoding: NSUTF8StringEncoding, error: nil)
    if url != nil {
        let docController = UIDocumentInteractionController(URL: url)
        docController.UTI = "public.comma-separated-values-text"
        docController.delegate = delegate
        docController.presentPreviewAnimated(true)
    }
}

(the delegate parameter is the view that calls the function, as in MyClass.ExportToCSV(self))

This works, mostly, and I see the following views:

However, in the Simulator I get the following warning:

Unbalanced calls to begin/end appearance transitions for <QLRemotePreviewContentController: 0x7fcd720da800>.

as well as

Unknown activity items supplied: ("<QLPrintPageRenderer: 0x7fcd73861ee0>","<UIPrintInfo: 0x7fcd714b9030>")

when I click the action button, then after a while

Communications error: <OS_xpc_error: <error: 0x10e032b10> { 
    count = 1, contents = "XPCErrorDescription" 
    => <string: 0x10e032f18> { length = 22, contents = "Connection interrupted" }
}>

and when I click Mail there is a crash with the following error:

viewServiceDidTerminateWithError: Error Domain=_UIViewServiceInterfaceErrorDomain 
    Code=3 "The operation couldn’t be completed. (_UIViewServiceInterfaceErrorDomain error 3.)" 
    UserInfo=0x7fcd71631460 {Message=Service Connection Interrupted}
<MFMailComposeRemoteViewController: 0x7fcd73864aa0> timed out waiting for fence 
    barrier from com.apple.MailCompositionService

Although on the actual device everything works as planned, so many errors throw me off a bit. Is there a better solution?

Upvotes: 3

Views: 6350

Answers (1)

zisoft
zisoft

Reputation: 23078

This is probably due to objects already have been deallocated when they are accessed by the mail or printing app. Try to declare your docController and url variables as class properties so they keep alive as long as the view controller exists.

Upvotes: 1

Related Questions