Darshit Shah Darshit Shah - 5 months ago 18
iOS Question

How can I return function value from block body?

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)'

Answer

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