0

I've come across a weird issue that I've spent ages working on.

I'm basically trying to get the filepath of a photo out of the asset library and draw it on a pdf using the CGRectMake method using the code below:

In the .h file:

@property (strong, nonatomic) UIImage *pdfSnagImage;

In the .m file:

NSURL *url = [[NSURL alloc] initWithString:pdf.photo];
ALAssetsLibrary* library = [[ALAssetsLibrary alloc] init];

[library assetForURL:url resultBlock:^(ALAsset *asset) {

    ALAssetRepresentation *rep = [asset defaultRepresentation];            
    self.filename = [rep filename];
    NSLog(@"filename for image is: %@", self.filename);

    CGImageRef iref = [rep fullResolutionImage];
    if (iref) {
        self.pdfImage = [UIImage imageWithCGImage:iref];
        NSLog(@"image height %f", self.pdfImage.size.height);

    }

} failureBlock:^(NSError *error) {

    NSLog(@"Couldn't load asset %@ => %@", error, [error localizedDescription]);

}];

UIImage *testImage = self.pdfImage;

[testImage drawInRect:CGRectMake( (pageSize.width - testImage.size.width/2)/2, 350, testImage.size.width/2, testImage.size.height/2)];

What's happening is that the UIImage after the block, testImage is actually being resolved before the block - therefore it is Null, as self.pdfImage is only set within the block.

If I put those lines of code in the block I get an error with the CGRectMake method, Invalid Context 0x0.

How on earth can I assign the self.pdfImage UIImage first then draw it?

jcrowson
  • 4,290
  • 12
  • 54
  • 77
  • What context are you drawing into? The method `assetForURL:resultBlock:failureBlock:` returns straight away and then goes and does it's work asynchronously before calling the code in either `resultBlock` or `failureBlock`. Therefore you need to be doing your work inside of either of those blocks. – Paul.s Apr 03 '12 at 00:09
  • The following SO question seems relevant: http://stackoverflow.com/questions/7234445/wait-for-assetforurl-blocks-to-be-completed – lukasz Apr 03 '12 at 02:54
  • @Paul.s Could you explain what you mean by what context am I drawing into? – jcrowson Apr 03 '12 at 08:18

1 Answers1

1

The block is executed asynchronously...it's being executed on a separate thread. This is the design of the assets lib api.

user953175
  • 205
  • 3
  • 9