MFMailComposeViewController花了很长时间才发送电子邮件

时间:2019-01-29 18:14:01

标签: ios swift mfmailcomposeviewcontroller messageui

我正在构建一个应用程序,需要在其中添加附件并通过电子邮件发送多张照片。为此,我将照片保存到相机VC的磁盘中,并在电子邮件VC的viewDidLoad()中访问它们。我将它们作为.pngData()存储在数组中,并使用以下代码将它们附加到MFMailComposeViewController中:

func configuredMailComposeViewController() -> MFMailComposeViewController {

    let mailComposerVC = MFMailComposeViewController()
    mailComposerVC.mailComposeDelegate = self

    mailComposerVC.setToRecipients([UserDefaults.standard.string(forKey: "Email")!])
    mailComposerVC.setSubject("Заявление")
    mailComposerVC.setMessageBody("\(ProtocolText.text!)", isHTML: false)

    // unpacking images from array and attaching them to Email

    var dataName = 0
    for data in imageData {
        dataName += 1
        mailComposerVC.addAttachmentData(data, mimeType: "image/png", fileName: "\(dataName).png")
    }

    return mailComposerVC

}

这些是我的“保存”和“获取”方法:

func loadImage(fileName: String) -> UIImage? {

    let documentDirectory = FileManager.SearchPathDirectory.documentDirectory

    let userDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(documentDirectory, userDomainMask, true)

    if let dirPath = paths.first {
        let imageUrl = URL(fileURLWithPath: dirPath).appendingPathComponent(fileName)
        let image = UIImage(contentsOfFile: imageUrl.path)
        return image

    }

    return nil
}

    // Used in CameraViewController
func saveImage(imageName: String, image: UIImage) {


    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first else { return }

    let fileName = imageName
    let fileURL = documentsDirectory.appendingPathComponent(fileName)
    guard let data = image.jpegData(compressionQuality: 1) else { return }

    //Checks if file exists, removes it if so.
    if FileManager.default.fileExists(atPath: fileURL.path) {
        do {
            try FileManager.default.removeItem(atPath: fileURL.path)
            print("Removed old image")
        } catch let removeError {
            print("couldn't remove file at path", removeError)
        }

    }

    do {
        try data.write(to: fileURL)
    } catch let error {
        print("error saving file with error", error)
    }

}

由于某些原因,图像会附着,但是电子邮件至少需要15秒才能发送。 “发送”按钮只是卡住了。我不知道为什么请帮忙。

1 个答案:

答案 0 :(得分:1)

图像的重量有问题。一幅图像以前的重量为6848.7939453125 KB。由于我有多张图像,因此花了很多时间来处理它们。使用image.jpegData(compressionQuality: CGFloat)!)方法压缩它们可以解决所有问题。感谢Mark Thormann提出修复建议!