Я создаю приложение, которое отправляет электронное письмо с последней сделанной фотографией (скриншот), я застрял при добавлении последней сделанной фотографии.
Я пытался искать везде и нашел только код извлеченияно не понимал и не знал, как реализовать это в моем коде
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()
}
РЕДАКТИРОВАТЬ: я попробовал то, что предложил @ user3344236, и я получил ошибку при возвращении изображения!:
func getImage(asset: PHAsset) -> UIImage{
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
fetchOptions.fetchLimit = 1
let fetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions)
if (fetchResult.firstObject != nil) {
var lastAsset: PHAsset = fetchResult.lastObject as! PHAsset
var image = UIImage()
PHImageManager.default().requestImage(for: lastAsset, targetSize: CGSize(width: 100, height: 100) , contentMode: .aspectFill, options: PHImageRequestOptions(), resultHandler: { (result, info) -> Void in
image = result!
})
return image! //Cannot force unwrap value of non-optional type 'UIImage'
}
}