0
votes

I have function where return type is 'BOOL' and in function body Calling HTTP request.

If data exist I want to return 'True'. I want to manage synchronously.

- (BOOL) randomFunction {
        NSURLSession *session = [NSURLSession sharedSession];
        [[session dataTaskWithRequest:mutableRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
            if (data) {
                NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];
                NSString *status = (NSString *)[JSON valueForKey:@"enabled"];
                if ([status isEqualToString:@"true"]) {
    //                return YES; // ERROR
                }
            }
    //       return NO; // ERROR
        }] resume];
}

ERROR:

Incompatible block pointer types sending 'BOOL (^)(NSData * _Nullable __strong, NSURLResponse * _Nullable __strong, NSError * _Nullable __strong)' to parameter of type 'void (^ _Nonnull)(NSData * _Nullable __strong, NSURLResponse * _Nullable __strong, NSError * _Nullable __strong)'

1
No you don't want it synchronously. Even if you want, it's a bad idea, it will block your app during web call (imagine people in metro, no network, your app has to be killed). Check up my answer, I updated it to fit your needs. - AnthoPak
@AnthoninC. thanks for pointing out about dark side of synchronous call in my case... - Darshit Shah
No problem buddy, glad to have helped. - AnthoPak

1 Answers

1
votes

You can't return value in a block, because it is asynchronous. What you can do instead is using a completionHandler to send result. Here is a sample code :

-(void)randomFunction:(void (^)(BOOL response))completionHandlerBlock {
    NSURLSession *session = [NSURLSession sharedSession];
    [[session dataTaskWithRequest:nil completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (data) {
            NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];
            NSString *status = (NSString *)[JSON valueForKey:@"enabled"];
            if ([status isEqualToString:@"true"]) {
                completionHandlerBlock(YES);
            }
        }
        completionHandlerBlock(NO);
    }] resume];
}

and use it like that :

[self randomFunction:^(BOOL response) {
    if (response) {
        //handle response
    }
}];