How to check if an ALAsset still exists using a URL

前端 未结 4 897
悲哀的现实
悲哀的现实 2020-12-05 11:57

I\'ve got an array containing ALAsset urls (not full ALAsset objects) So each time I start my application I want to check my array to see if it\'s still up to date...

<
4条回答
  •  有刺的猬
    2020-12-05 12:23

    Having assets path you can use this function to check if image exist:

    -(BOOL) imageExistAtPath:(NSString *)assetsPath
    {  
        __block BOOL imageExist = NO; 
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
            if (asset) {
                imageExist = YES;
                }
        } failureBlock:^(NSError *error) {
            NSLog(@"Error %@", error);
        }];
        return imageExist;
    }
    

    Remember that checking if image exist is checking asynchronyus. If you want to wait until new thread finish his life call function "imageExistAtPath" in main thread:

    dispatch_async(dispatch_get_main_queue(), ^{
        [self imageExistAtPath:assetPath];
    });
    

    Or you can use semaphores, but this is not very nice solution:

    -(BOOL) imageExistAtPath:(NSString *)assetsPath
    {  
        __block BOOL imageExist = YES; 
        dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);   
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);   
        dispatch_async(queue, ^{  
            ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
            [library assetForURL:[NSURL URLWithString:assetsPath] resultBlock:^(ALAsset *asset) {
                if (asset) {
                    dispatch_semaphore_signal(semaphore); 
                } else {
                    imageExist = NO;
                    dispatch_semaphore_signal(semaphore); 
                    }
            } failureBlock:^(NSError *error) {
                 NSLog(@"Error %@", error);
            }];
        });
        dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); 
        return imageExist;
    }
    

提交回复
热议问题