stefanosn
stefanosn

Reputation: 3324

How to return boolean from a block in objective c?

Hello everyone trying to return a boolean to the method i called from within a block after the user selects the option to allow or not access to photolibrary. How can i return a boolean from this specific block?

(BOOL)checkIfUserHasAccessToPhotosLibrary{
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];
   
        if (status == PHAuthorizationStatusNotDetermined) {

        NSLog(@"Access has not been determined check again");
            __block BOOL boolean=false;
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            
             if (status == PHAuthorizationStatusAuthorized) {
               
                 NSLog(@"User responded has access to photos library");
                 boolean=true;
  
             }

             else {
                 
                 NSLog(@"User responded does has access to photos library");
                 boolean=false;
                 
             }

         }];
    }

}

Upvotes: 2

Views: 863

Answers (1)

Rob
Rob

Reputation: 437482

You asked:

How to return boolean from a block in objective c?

You don’t.

You employ a completion handler block parameter in your method, perhaps like so:

- (void)checkPhotosLibraryAccessWithCompletion:(void (^ _Nonnull)(BOOL))completion {
    PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus];

    if (status == PHAuthorizationStatusNotDetermined) {
        [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) {
            completion(status == PHAuthorizationStatusAuthorized);
        }];
    } else {
        completion(status == PHAuthorizationStatusAuthorized);
    }
}

And then you would use it like so:

[self checkPhotosLibraryAccessWithCompletion:^(BOOL success) {
    // use success here

    if (success) {
        ...
    } else {
        ...
    }
}];

// but not here, because the above runs asynchronously (i.e. later)

Upvotes: 1

Related Questions