简体   繁体   English

Swift 3通过电子邮件发送PHAsset图像

[英]Swift 3 Email a PHAsset Image

I am trying to send a PHAsset image over email. 我正在尝试通过电子邮件发送PHAsset图像。 I am first trying to get a base case going in a sandbox app, and then I want to eventually iterate over an array of PHAssets. 我首先尝试在沙盒应用程序中获得一个基本案例,然后最终要遍历一组PHAsset。 Below is my sandbox code, followed by a couple of questions/issues I am having. 以下是我的沙盒代码,后面是几个问题。 (Some of this code snippet came from this SO post .) And this is all part of trying to implement the multi-asset picker I found called TLPHAssets , which looked to be the most Swift-4 / PHAsset current version from this list on another SO post . (一些代码片段来自此SO帖子 。)这是尝试实现我发现的名为TLPHAssets的多资产选择器的全部部分,该选择器看起来是该列表中另一个列表中最Swift-4 / PHAsset当前版本所以帖子

func dismissPhotoPicker(withTLPHAssets: [TLPHAsset]) {
    // use selected order, fullresolution image

    self.selectedAssets = withTLPHAssets

    let mail = MFMailComposeViewController()
    mail.mailComposeDelegate = self;
    mail.setToRecipients(["emailaddress.com"])
    // Put the rest of the email together and present the draft to the user
    mail.setSubject("Subject")

    let options = PHImageRequestOptions()
    options.isNetworkAccessAllowed = true
    options.version = .current
    options.deliveryMode = .opportunistic
    options.resizeMode = .fast
    let asset : PHAsset = self.selectedAssets[0].phAsset! as PHAsset
    PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width : 400, height : 400), contentMode: .aspectFit, options: options, resultHandler: {(result: UIImage!, info) in
        if let image = result
        {
            let imageData: NSData = UIImageJPEGRepresentation(image, 1.0)! as NSData
            mail.addAttachmentData(imageData as Data, mimeType: "image/jpg", fileName: "BeforePhoto.jpg")
        }
    })

Two questions (I'm pretty new to Swift so apologies if I'm missing something basic): 两个问题(我是Swift的新手,如果我缺少基本知识,我们深表歉意):

  1. I'm having trouble getting the resultHandler block of code to ever get executed. 我在获取resultHandler代码块来执行时遇到了麻烦。 I had targetSize set to PHImageManagerMaximumSize, but then changed it to 400x400 on another post's recommendation (by the way, I'm just picking an image from my camera roll and I've confirmed in my test case that the mediaType of the PHAsset is 'image'; not working with Live Photo or Video yet, although I plan to tackle those next, and I'll add a switch statement to ensure I call the right asset-request Handler). 我已将targetSize设置为PHImageManagerMaximumSize,但根据另一篇文章的建议将其更改为400x400(顺便说一句,我只是从相机胶卷中选取一张图像,并且在我的测试案例中已确认PHAsset的mediaType为'图像”;虽然我计划接下来解决这些问题,但还不能使用Live Photo或Video,并且我将添加一个switch语句以确保调用正确的资产请求处理程序。 Why wouldn't PHImageManagerMaximumSize work? 为什么PHImageManagerMaximumSize不起作用? And when I run the app in the simulator and pick one of the five canned images, I still can't get into the resultHandler block of code (and those are all mediaType 'image'). 而且,当我在模拟器中运行该应用并选择五个罐装图像之一时,我仍然无法进入resultHandler代码块(这些都是mediaType'image')。 Any idea what might be wrong with my requestImage call that is preventing the resultHandler from being called? 知道我的requestImage调用有什么问题会阻止resultHandler被调用吗?

  2. I did eventually get an image from my camera roll to cause the resultHandler code to be called with targetSize at 400x400. 最终,我确实从相机胶卷中获取了一个图像,从而导致使用400x400的targetSize调用resultHandler代码。 But now inside the resultHandler, my sandbox app is crashing on the "let imageData: NSData ..." line with "2017-10-26 15:35:26.604997-0700 MultiAssetPicker[15766:4904592] fatal error: unexpectedly found nil while unwrapping an Optional value". 但是现在在resultHandler内,我的沙盒应用程序崩溃,并在“ let imageData:NSData ...”行上显示为“ 2017-10-26 15:35:26.604997-0700 MultiAssetPicker [15766:4904592]”致命错误:意外地发现nil时解开可选值”。

Any and all help very much appreciated. 任何和所有帮助非常感谢。

I figured it out. 我想到了。 The key was to was to set isSynchronous to true in PHImageRequestOptions. 关键是要在PHImageRequestOptions中将isSynchronous设置为true。 The latest code that got me through these issues is below, although I wouldn't call it production just yet (needs more testing). 使我能够解决这些问题的最新代码如下,尽管我现在还不称其为生产(需要更多测试)。

                    // Set up the image-request options
                    let options = PHImageRequestOptions()
                    options.isNetworkAccessAllowed = true
                    options.version = .current
                    options.deliveryMode = .opportunistic
                    options.isSynchronous = true
                    options.resizeMode = .fast

                    // For each photo asset the user selected
                    for i in 0..<self.selectedAssets.count {

                        // Convert to a PHAsset
                        let asset : PHAsset = self.selectedAssets[i].phAsset! as PHAsset

                        // Request the underlying asset as an image
                        PHImageManager.default().requestImage(for: asset, targetSize: CGSize(width : 400, height : 400), contentMode: .aspectFill, options: options, resultHandler: {(result: UIImage!, info) in

                            // If the asset is in fact an image, attach it to the email being composed
                            switch self.selectedAssets[i].phAsset?.mediaType {
                            case .image?:
                                print("Image \(i)")
                                let imageData: NSData = UIImageJPEGRepresentation(result!, 0.9)! as NSData
                                mail.addAttachmentData(imageData as Data, mimeType: "image/jpg", fileName: "Attachment\(i).jpg")
                            case .video?:
                                print("Video not supported.")
                            case .audio?:
                                print("Audio not supported")
                            default:
                                print("Unknown")
                            }
                        })
                    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM