2

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

         }];
    }

}
stefanosn
  • 3,264
  • 10
  • 53
  • 79

1 Answers1

1

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)
Rob
  • 415,655
  • 72
  • 787
  • 1,044
  • thanks for the suggestion Mr. Rob. I tried it and i get *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Modifications to the layout engine must not be performed from a background thread after it has been accessed from the main thread.' - then i tried using dispatch_async(dispatch_get_main_queue(), ^{ [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status) { completion(status == PHAuthorizationStatusAuthorized); }]; }); but still i get same exception... – stefanosn Feb 05 '22 at 16:20
  • Never mind i just had to add dispatch_async(dispatch_get_main_queue(), ^{ if (success) { ... } else { ... } }); also . Its working so i will accept your answer as right. Thanks so much for your help Mr. Rob i appreciate it! – stefanosn Feb 05 '22 at 16:30