ios programming: Using threads to add multiple images to library

前端 未结 3 1542
鱼传尺愫
鱼传尺愫 2021-01-14 12:21

In Xcode, when I\'m trying to add more than 5 images to my library, it gives me the following error:

Error Domain=ALAssetsLibraryErrorDomain         


        
3条回答
  •  情话喂你
    2021-01-14 13:00

    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];
        }];
    }
    

    Usage:

    [foo writeImages:[foo.images mutableCopy] completion:^(id result){
        // Caution: check the execution context - it may be any thread
        NSLog(@"Result: %@", result);   
    }];
    

提交回复
热议问题