I'm making an app that sends an email with the last photo taken (screenshot) attached, I'm stuck at adding the last photo taken.
I tried searching everywhere and only found the fetch code but didn't understand it and didn't know how to implement it in my code
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()
}
EDIT: i tried what @user3344236 suggested and i got error at return image!:
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'
}
}