Pass CollectionView photo to Email Attachment iOS

2019-06-13 14:45发布

问题:

I've choose some photo from the photo library and populated into the collectionView. Then my collection view will have some photos inside. Here is my code for getting the photos into collection view.

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell: PhotoCollectionViewCell = collectionView.dequeueReusableCellWithReuseIdentifier("PhotoCell", forIndexPath: indexPath) as! PhotoCollectionViewCell
    let asset : PHAsset = self.photoAsset[indexPath.item] as! PHAsset
    PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in
        if let image = result
        {
            cell.setThumbnailImage(image)
        }
    })
    return cell
}

However, how do I pass all these photo which are located in the collection View to the email attachment? Below code is the email attachment, how do I pass all the photos into this attachment?

let emailTitle = "Email Us"
let messageBody = "Location: \(sendLocation) \n\n \(sendContent)"
let toReceipients = ["testing@gmail.com"]
let mc : MFMailComposeViewController = MFMailComposeViewController()
mc.mailComposeDelegate = self
mc.setSubject(emailTitle)
mc.setMessageBody(messageBody, isHTML: false)
mc.setToRecipients(toReceipients)
self.presentViewController(mc, animated: true, completion: nil)

回答1:

The same way you get the image from the you can get the PHImageManager, you can get all such images and just attach to mail. Or if you want to attach ALL images, then you can add all the loaded images to an array and attach those to mail like:

let asset : PHAsset = self.photoAsset[indexPath.item] as! PHAsset
    PHImageManager.defaultManager().requestImageForAsset(asset, targetSize: PHImageManagerMaximumSize, contentMode: .AspectFill, options: nil, resultHandler: {(result, info)in
        if let image = result
        {
            cell.setThumbnailImage(image)
            self.arr.append(image)
        }
    })

Then add all the images from the arr to mail composer, like

func composeMail() {
        let mailComposeVC = MFMailComposeViewController()

        for image in arr {
                let photoData : NSData = UIImagePNGRepresentation(image)!
                mailComposeVC.addAttachmentData(UIImageJPEGRepresentation(photoData, CGFloat(1.0))!, mimeType: "image/jpeg", fileName:  "test.jpeg")   
        }
        mailComposeVC.setSubject("Email Subject")
        self.presentViewController(mailComposeVC, animated: true, completion: nil)

    }