iphone - MFMailComposeViewController : Attaching Images from Photo Gallery

标签 iphone ios ios5 alassetslibrary messageui

我在将照片库中的图像附加到电子邮件时遇到了一些问题。

基本上,我的应用程序的一项功能允许用户拍照。当他们拍摄照片时,我会在 Core Data 中记录对图像的 URL 引用。我知道您必须通过ALAssetRepresentation到达图像。当用户想要查看他们拍摄的图像时,我在我的应用程序中启动并运行了它。

我现在正试图允许用户将所有为事件拍摄的照片附加到电子邮件中。在执行此操作时,我遍历存储 URL 引用的核心数据实体,调用返回 UIImage 的方法。来自 ALAssetsLibrary然后使用 NSData 附加它/UIImageJPEGRepresentationMFMailComposeViewController/addAttachmentData方法。

问题是:当电子邮件呈现给用户时,有代表图像的蓝色小方 block ,并且没有附加图像。

这是代码:

- (void)sendReportReport
{

    if ([MFMailComposeViewController canSendMail])
    {

        MFMailComposeViewController *mailer = [[MFMailComposeViewController alloc] init];

        mailer.mailComposeDelegate = self;

        [mailer setSubject:@"Log: Report"];

        NSArray *toRecipients = [NSArray arrayWithObjects:@"someone@someco.com", nil];
        [mailer setToRecipients:toRecipients];


        NSError *error;

        NSFetchRequest *fetchPhotos = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription 
                                       entityForName:@"Photo" inManagedObjectContext:__managedObjectContext];
        [fetchPhotos setEntity:entity];
        NSArray *fetchedPhotos = [__managedObjectContext executeFetchRequest:fetchPhotos error:&error];
        int counter;

        for (NSManagedObject *managedObject in fetchedPhotos ) {
            Photo *photo = (Photo *)managedObject;

//            UIImage *myImage = [UIImage imageNamed:[NSString stringWithFormat:@"%@.png", counter++]];
            NSData *imageData = UIImageJPEGRepresentation([self getImage:photo.referenceURL], 0.5);
//            NSData *imageData = UIImagePNGRepresentation([self getImage:photo.referenceURL]);
//            [mailer addAttachmentData:imageData mimeType:@"image/jpeg" fileName:[NSString stringWithFormat:@"%i", counter]];  
            [mailer addAttachmentData:imageData mimeType:@"image/jpeg" fileName:[NSString stringWithFormat:@"a.jpg"]];  

            counter++;

        }


        NSString *emailBody = [self getEmailBody];

        [mailer setMessageBody:emailBody isHTML:NO];

        [self presentModalViewController:mailer animated:YES];

    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                        message:@"Your device doesn't support the composer sheet"
                                                       delegate:nil
                                              cancelButtonTitle:@"OK"
                                              otherButtonTitles:nil];
        [alert show];

    }

}

以及返回 UIImage 的方法:
#pragma mark - Get Photo from Asset Library
+ (ALAssetsLibrary *)defaultAssetsLibrary {
    static dispatch_once_t pred = 0;
    static ALAssetsLibrary *library = nil;
    dispatch_once(&pred, ^{
        library = [[ALAssetsLibrary alloc] init];
    });
    return library; 
}

- (UIImage *)getImage:(NSString *)URLReference
{

    __block UIImage *xPhoto = nil;

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {
        UIImage *xImage;

        // get the image
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        CGImageRef iref = [rep fullScreenImage];

        if (iref) {
            xImage = [UIImage imageWithCGImage:iref];
        }

        xPhoto = xImage;

    };


    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"Error fetching photo: %@",[myerror localizedDescription]);
    };


    NSURL *asseturl = [NSURL URLWithString:URLReference];

    // create library and set callbacks
    ALAssetsLibrary *al = [DetailsViewController defaultAssetsLibrary];
    [al assetForURL:asseturl 
        resultBlock:resultblock
       failureBlock:failureblock];   

    return xPhoto;

}

注意:上面的代码确实运行,它只是不附加图像。另外,请注意,只要我将它们设置为 UIImageView,我就可以在我的应用程序中成功附加图库中的图像。 .Image 已经(基本上,我从 UIImageView 获取指向图像的指针并将其传递给 addAttachmentData 方法。)这只是当我尝试遍历核心数据并附加而不首先将图像设置为UIImageView我有麻烦了。

任何提示将非常感谢!

谢谢!
杰森

最佳答案

哦,现在我明白了.. sry。您正在使用异步 block 从 Assets 库中获取图像。但是在开始该操作后,您将返回 xImage .但异步操作将在稍后完成。所以你返回零。

你需要像这样改变你的架构师:

在您的 .h 文件中,您需要两个新成员:

NSMutableArray* mArrayForImages;
NSInteger mUnfinishedRequests;

在你的 .m 文件中这样做:
- (void)sendReportReport
{
    // save image count
    mUnfinishedRequests = [fetchedPhotos count];

    // get fetchedPhotos
    [...]

    // first step: load images
    for (NSManagedObject *managedObject in fetchedPhotos )
    {
        [self loadImage:photo.referenceURL];    
    }
}

将您的 getImage 方法更改为 loadImage:
- (void)loadImage:(NSString *)URLReference
{
    NSURL *asseturl = [NSURL URLWithString:URLReference];

    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
    {    
        // get the image
        ALAssetRepresentation *rep = [myasset defaultRepresentation];
        CGImageRef iref = [rep fullScreenImage];

        if (iref) {
            [mArrayForImages addObject: [UIImage imageWithCGImage:iref]];
        } else {
            // handle error
        }

        [self performSelectorOnMainThread: @selector(imageRequestFinished)];
    };

    ALAssetsLibraryAccessFailureBlock failureblock  = ^(NSError *myerror)
    {
        NSLog(@"Error fetching photo: %@",[myerror localizedDescription]);

        [self performSelectorOnMainThread: @selector(imageRequestFinished)];
    };


    // create library and set callbacks
    ALAssetsLibrary *al = [DetailsViewController defaultAssetsLibrary];
    [al assetForURL:asseturl 
        resultBlock:resultblock
       failureBlock:failureblock];
}

创建一个新的回调方法:
- (void) imageRequestFinished
{
    mUnfinishedRequests--;
    if(mUnfinishedRequests <= 0)
    {
       [self sendMail];
    }
}

在获取图像后,还有一种最终发送邮件的额外方法:
- (void) sendMail
{
    // crate mailcomposer etc
    [...]

    // attach images
    for (UIImage *photo in mArrayForImages )
    {
                NSData *imageData = UIImageJPEGRepresentation(photo, 0.5);
                [mailer addAttachmentData:imageData mimeType:@"image/jpeg" fileName:[NSString stringWithFormat:@"a.jpg"]];
    }

    // send mail
    [...]
}

关于iphone - MFMailComposeViewController : Attaching Images from Photo Gallery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9587485/

相关文章:

iphone - TTTableViewController 用对象数组变量填充数据源

ios - 如何解决 NSInvalidArgumentException 错误?

ios - Spritekit removeFromParent() 关于 iOS9 的问题

c++ - 在 C++/iOS 中更改默认除以 0 的行为

iphone - 收到的远程通知没有出现在通知中心,但出现了应用程序图标上的角标(Badge)编号

iphone - 如何从核心数据中获取唯一字段值(song_type)

iphone - 在UITableViewController中的viewWillAppear之后未调用didDeselectRowAtIndexPath

ios - 照片框架工作异常。

opengl-es - 使用 CVPixelBufferRef 和 Shaders 在 ffmpeg 的 OpenGL 中渲染 YUV 视频

具有来自服务器 : Socket (using streams) or Apple Push Notification service? 的实时更新的 iOS 应用程序