In Xcode, when I\'m trying to add more than 5 images to my library, it gives me the following error:
Error Domain=ALAssetsLibraryErrorDomain
Dispatch_async
is something to do in background , so I put your for{}
and function call inside the dispatch_async
body
so putting for
inside the dispatch async
will store your imaged in the album,like just running for
. but on seperate thread.
dispatch_queue_t myQueue = dispatch_queue_create("com.cropr.myqueue", 0);
dispatch_async(myQueue, ^{
for (UIImage * image in images)
UIImageWriteToSavedPhotosAlbum((__bridge UIImage *)(image),self,nil,nil);
});
}
You can also try this. i think will be better, watch if it works , then add what you want to handle the errors.
Also i think here is your desired answer : iOS: dispatch_async and UIImageWriteToSavedPhotosAlbum
I'd recommend using an NSOperationQueue
and play with the value of maxConcurrentOperationCount
. This way you can control the number of simultaneous writes to the library, and not overwhelm it.
If you use threads, or even GCD, you'd need to implement this logic yourself. More code --> more chance of introducing a bug.
You may try to write all your images subsequently, instead of simultaneously. The following code utilizes ALAssetsLibrary
, and implements an "asynchronous loop" which invokes a number of asynchronous methods in sequence.
typedef void (^completion_t)(id result);
- (void) writeImages:(NSMutableArray*)images
completion:(completion_t)completionHandler {
if ([images count] == 0) {
if (completionHandler) {
// Signal completion to the call-site. Use an appropriate result,
// instead of @"finished" possibly pass an array of URLs and NSErrors
// generated below in "handle URL or error".
completionHandler(@"finished");
}
return;
}
UIImage* image = [images firstObject];
[images removeObjectAtIndex:0];
[self.assetsLibrary writeImageToSavedPhotosAlbum:image.CGImage
orientation:ALAssetOrientationUp
completionBlock:^(NSURL *assetURL, NSError *error)
{
// Caution: check the execution context - it may be any thread,
// possibly use dispatch_async to dispatch to the main thread or
// any other queue.
// handle URL or error
...
// next image:
[self writeImages:images completion:completionHandler];
}];
}
[foo writeImages:[foo.images mutableCopy] completion:^(id result){
// Caution: check the execution context - it may be any thread
NSLog(@"Result: %@", result);
}];