保存文件并作为电子邮件附件发送

时间:2016-01-22 13:02:48

标签: ios swift nsdocumentdirectory

我试图从Parse获取字符串并将其保存到文件中,以便通过电子邮件发送。问题是当我尝试发送电子邮件时文件不存在。

func openActions() {
    actions = UIAlertController(title: "", message: "", preferredStyle: .ActionSheet)
    let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: {
        (action) -> Void in
        self.actions?.dismissViewControllerAnimated(true, completion: nil)
    })

    let saveCSV = UIAlertAction(title: "Save as CSV", style: .Default, handler: {
        (action) -> Void in
        self.getAndSaveItems()
        self.writeToFile()
        self.actions?.dismissViewControllerAnimated(true, completion: nil)
    })

    let emailFile = UIAlertAction(title: "Email CSV", style: .Default, handler: {
        (action) -> Void in
        self.emailFile()
        self.actions?.dismissViewControllerAnimated(true, completion: nil)
    })

    actions?.addAction(cancelAction)
    actions?.addAction(emailFile)
    actions?.addAction(saveCSV)
    self.presentViewController(actions!, animated: true, completion: nil)
}

func dataFilePath() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    let titleString = self.title!.stringByReplacingOccurrencesOfString(" ", withString: "_")
    let string = String(format: "%@.csv", titleString)
    return documentsDirectory.stringByAppendingString(string)
}

func getAndSaveItems() {
    let getLimit = 1000
    var getSkip = 0
    // var names = [String]()
    // var upcs = [String]()
    // var models = [String]()
    // var ids = [String]()
    // var prices = [String]()
    // var notes = [String?]()

    activityIndicator?.startAnimating()

    let query = PFQuery(className: "Items")
    query.whereKey("user", equalTo: PFUser.currentUser()!)
    query.whereKey("collection", equalTo: self.title!)
    query.orderByAscending("item")
    query.limit = getLimit
    query.skip = getSkip
    query.findObjectsInBackgroundWithBlock( {
        (objects, error) -> Void in
        if error == nil {
            if let objects = objects as [PFObject]! {
                for object in objects {
                    self.names.append(object["item"] as! String)
                    self.upcs.append(object["upc"] as! String)
                    self.ids.append(object.objectId!)
                    self.models.append(object["model"] as! String)
                    self.prices.append(object["pricePaid"] as! String)
                    if object["notes"] == nil {
                        self.notes.append(nil)
                    } else {
                        self.notes.append(object["notes"] as? String)
                    }
                }
            }

            if objects!.count == getLimit {
                getSkip += getLimit
                self.getAndSaveItems()
            }
        } else {
            // Show error...
        }
    })
}

func writeToFile() {
    if (!NSFileManager.defaultManager().fileExistsAtPath(self.dataFilePath())) {
        NSFileManager.defaultManager().createFileAtPath(self.dataFilePath(), contents: nil, attributes: nil)
    }

    // var writeString = NSMutableString(capacity: 0)
    var writeString = String()
    writeString.reserveCapacity(0)

    for (var i = 0; i < names.count; i++) {
        let stringToWrite = String(format: "%@, %@, %@, %@, %@", ids[i], names[i], models[i], upcs[i], prices[i])
        writeString.appendContentsOf(stringToWrite)
    }

    let handle = NSFileHandle(forWritingAtPath: self.dataFilePath())
    handle?.truncateFileAtOffset((handle?.seekToEndOfFile())!)
    handle?.writeData(writeString.dataUsingEncoding(NSUTF8StringEncoding)!)

    self.activityIndicator?.stopAnimating()
}

func emailFile() {
    if (NSFileManager.defaultManager().fileExistsAtPath(dataFilePath())) {
        if MFMailComposeViewController.canSendMail() {
            let mailComposer = MFMailComposeViewController()
            mailComposer.mailComposeDelegate = self
            let subject = String(format: "My %@ Collection", self.title!)
            mailComposer.setSubject(subject)
            mailComposer.setMessageBody("", isHTML: false)

            let fileData = NSData(contentsOfFile: dataFilePath())
            mailComposer.addAttachmentData(fileData!, mimeType: "text/csv", fileName: "")

            self.presentViewController(mailComposer, animated: true, completion: nil)
        } else {
            // Can't send mail...
        }
    } else {
        // File doesn't exist...
        print("File doesn't exist")
    }
}

func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
    self.dismissViewControllerAnimated(true, completion: nil)
}

1 个答案:

答案 0 :(得分:0)

我在文件路径中忘记了“/”。一旦我添加了它,它工作正常。