在 Xcode 中,当我尝试将 超过 5 张图像 添加到我的库时,它给了我以下错误:

Error Domain=ALAssetsLibraryErrorDomain Code=-3301 "Write busy" UserInfo=0xa706aa0 {NSLocalizedRecoverySuggestion=Try to write again, NSLocalizedFailureReason=There was a problem writing this asset because the writing resources are busy., NSLocalizedDescription=Write busy, NSUnderlyingError=0xa770110 "Write busy"}

为了解决这个问题,我想出线程可以解决我的问题。文档说明我可以使用 POSIX 线程或 NSThreads 。当我尝试使用 POSIX 线程时,我将我的线程设置为可连接的,并且我正在创建一个 void * 函数:
void * myFunc (void * image)
{
       UIImageWriteToSavedPhotosAlbum((__bridge UIImage *)(image),self,nil,nil);
       pthread_exit(NULL);
       return NULL;
}

我也在等待线程结束。但仍然只写了 5 个图像。

我试过使用 NSThreads 并做了:
[self performSelectorOnMainThread:@selector(myFunc:) withObject:image waitUntilDone:YES];

但它仍然不起作用。

我的问题有答案吗?这对我的工作至关重要。

谢谢。

编辑:

也试过 dispatch_async 。这是错的吗?
dispatch_queue_t myQueue = dispatch_queue_create("com.cropr.myqueue", 0);

for (UIImage * image in images) {

        dispatch_async(myQueue, ^{

            [self.library saveImage:image toAlbum:@"Cropr" withCompletionBlock:^(NSError *error) {
                if (error!=nil) {
                    NSLog(@"Big error: %@", [error description]);
                }
            }];

        });

    }

我需要添加什么?

最佳答案

您可以尝试随后写入所有图像,而不是同时写入。下面的代码利用 ALAssetsLibrary ,并实现了一个“异步循环”,它依次调用了许多异步方法。

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

关于ios 编程 : Using threads to add multiple images to library,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20662908/

10-12 00:17
查看更多