clan
clan

Reputation: 353

ios synchronous network request handler returning result

The issue I am having is that my application has a thread that periodically needs make a series of network requests inside of a loop. Since this is inside of a separate thread and due to the nature of the requests (to a device on the local network and the response is simple) I want to do this synchronously. Network communication is a separate networking class than databaseController class.

I cannot get the method in networking class to return something from inside a completion handler

+ (void)GetMessages
{
   NSURLSession *session = [NSURLSession sharedSession];
   NSURLRequest *request = [networking makeAuthenticatedRequest:@"subpath.html"];
   //NSString* returnable;
   NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                                   completionHandler:
                              ^(NSData *data, NSURLResponse *response, NSError *error) {
                                  NSString* newStr = [[NSString alloc] initWithData:data
                                                         encoding:NSUTF8StringEncoding];
                                  //returnable = newStr;
                                  //return(newStr)
                                  NSLog(newStr);
                              }];
   [task resume];
}

the above code works but does not do anything except print the result of the request. when I try any of the commented out additions and the requisite changes nothing works. I have even tried to pass a reference to the calling object and update a property for storing the newStr inside the completion handler but even that does not work.

Is what I am trying possible? If so how?

I should probably add that the code needs to be compatible with ios 7-9.

Upvotes: 1

Views: 164

Answers (1)

barryjones
barryjones

Reputation: 2309

You need to do the following :

NSURLSession *session = [NSURLSession sharedSession];
NSMutableURLRequest *request =
[NSMutableURLRequest requestWithURL:[NSURL
                                     URLWithString:@"https://www.yahoo.com"]
                cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData
                    timeoutInterval:10
 ];

__block NSString* returnable; // notice the __block here
NSURLSessionDataTask *task = [session dataTaskWithRequest:request
                completionHandler:
                ^(NSData *data, NSURLResponse *response, NSError *error) {
                 NSString* newStr = [[NSString alloc] initWithData:data
                                    encoding:NSUTF8StringEncoding];
                 returnable = newStr;
                 // return(newStr); You cant return this here. Because the callback doesn't permit you to do so.
                 NSLog(@"%@", newStr);
        }];
[task resume];

Upvotes: 1

Related Questions