如何自动将最后拍摄的照片附加到Mail?

时间:2019-06-20 12:21:42

标签: ios swift mfmailcomposeviewcontroller

我正在制作一个应用程序,该应用程序发送带有最后拍摄的照片(屏幕截图)的电子邮件,但我坚持添加最后拍摄的照片。

我尝试在任何地方搜索,但只找到了获取代码,但不了解它,也不知道如何在我的代码中实现它

import 'package:flutter/material.dart';

import 'dart:math';

void main() {
  return runApp(
    MaterialApp(
      home: Scaffold(
        backgroundColor: Colors.red,
        appBar: AppBar(
          title: Center(child: Text('Dicee')),
          backgroundColor: Colors.red,
        ),
        body: DicePage(),
      ),
    ),
  );
}
class DicePage extends StatefulWidget {
  @override
  _DicePageState createState() => _DicePageState();
}

class _DicePageState extends State<DicePage> {
  @override
  Widget build(BuildContext context) {
    int leftDiceNumber = 5;
    int rightDiceNumber = 2;
    return Center(
      child: Row(
        children: <Widget>[
          Expanded(
            child: FlatButton(
              onPressed: (){
                setState(() {
                  leftDiceNumber = Random().nextInt(6) + 1;
                  print('$leftDiceNumber');
                });
              },
              child: Image.asset('images/dice$leftDiceNumber.png'),
            ),
          ),
          Expanded(
            child: FlatButton(
              onPressed: (){
                setState(() {
                  rightDiceNumber = Random().nextInt(6) + 1;
                  print('$rightDiceNumber');
                });
              },
              child: Image.asset('images/dice$rightDiceNumber.png'),
            ),
          ),
        ],
      ),
    );
  }
}  

编辑:我尝试了@ user3344236的建议,返回图像时出错!:

func takeScreenshot(){

        UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        UIImageWriteToSavedPhotosAlbum(image!, nil, nil, nil)

    }

    func sendMail(){
        let mail = MFMailComposeViewController()
        if MFMailComposeViewController.canSendMail(){
            mail.mailComposeDelegate = self
            mail.setToRecipients(["test@test.com"])
            mail.setSubject("Test mail subject")
            mail.setMessageBody("Test mail body", isHTML: false)
        } else {
            self.mailFailedToSent()
        }

    }

    func mailFailedToSent(){
        let mailFailedToSentAllert = UIAlertView(title: "Could not send mail", message: "You need to add Mail account in Settings > Passwords & Accounts > Add Account", delegate: self, cancelButtonTitle: "OK")
        mailFailedToSentAllert.show()
    }

    func mailComposeController(_ controller: MFMailComposeViewController, didFinishWith result: MFMailComposeResult, error: Error?) {
        controller.dismiss(animated: true, completion: nil)
    }

    @IBAction func reportButtonAction(_ sender: Any) {

        takeScreenshot()
        sendMail()
    }

0 个答案:

没有答案