Wait for assetForURL blocks to be completed

前端 未结 5 2088
离开以前
离开以前 2020-12-23 11:57

I would like to wait this code to be executed before to continue but as these blocks are called assynchronously I don\'t know how to do???

NSURL *asseturl;
N         


        
5条回答
  •  再見小時候
    2020-12-23 13:01

    This is an easy way to do it. Maybe not as elegant as using GCD but it should get the job done ... This will make your method blocking instead of non-blocking.

    __block BOOL isFinished = NO;
    NSURL *asseturl;
    NSMutableArray *tmpListAsset = [[NSMutableArray alloc] init];
    
    ALAssetsLibrary *library = [[[ALAssetsLibrary alloc] init];
    NSMutableArray *objectsToRemove = [[NSMutableArray alloc] init];
    for (NSDictionary *dico in assetsList) {
        asseturl = [NSURL URLWithString:[dico objectForKey:@"assetUrl"]];
        NSLog(@"asset url %@", asseturl);
        // Try to load asset at mediaURL
        [library assetForURL:asseturl resultBlock:^(ALAsset *asset) {
            // If asset doesn't exists
            if (!asset){
                [objectsToRemove addObject:dico];
            }else{
                [tmpListAsset addObject:[asseturl absoluteString]];
                NSLog(@"tmpListAsset : %@", tmpListAsset);
            }
            if (objectsToRemove.count + tmpListAsset.count == assetsList.count) {
                isFinished = YES;
            }
        } failureBlock:^(NSError *error) {
            // Type your code here for failure (when user doesn't allow location in your app)
            isFinished = YES;
        }];
    }
    
    while (!isFinished) {
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.01f]];
    }
    

提交回复
热议问题