0

I'm trying to use NSScanner to filter my response from a AFHTTPRequestOperation. The problem is I cannot return a string from the AFHTTPRequestOperation in my NSString method. Anyone have any ideas?

-(NSString*)queryResponseID {
//Find ID from https request
NSLog(@"Finding Location ID");
NSString *queryResponseID=@"";
NSString *clientID = @"myclientID";
if (!clientID) {
    NSLog(@"Need Clinet ID");

}




NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://api.domain.com/client_id=%@",clientID]]];



AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
                                     initWithRequest:request];
operation.responseSerializer = [AFJSONResponseSerializer serializer];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSLog(@"%@", responseObject);


} failure:nil];
[operation start];

queryResponseID = operation.responseString;


return queryResponseID;



}
Andrew Sheridan
  • 19
  • 1
  • 10

1 Answers1

0

Because the response is asynchronous so it hasn't arrived by the time your method returns. You need to collect the string in the success completion block and process it there (or in a method called from there) and remove the return statement you're currently using.


On top of that, I'd say what you're trying to do can be done more simply with a different approach. Rather than trying to use NSScanner on the raw JSON text you should filter the actual data objects. AFNetworking is already unpacking them for you (into responseObject), take advantage of that and use a combination of KVC, valueForKey: (the NSArray method) and NSPredicate to extract the information you want.

Wain
  • 118,658
  • 15
  • 128
  • 151
  • I have tried that and I get the following error: incompatible block pointer types sending 'NSString *(^)(AFHTTPRequestOperation *__strong, __strong id)' to parameter of type 'void (^)(AFHTTPRequestOperation *__strong, __strong id)' – Andrew Sheridan Apr 14 '14 at 17:18
  • You can not use return, at all, the success block processes the data / calls a method to process it. Returning is immediate (synchronous) and that is not possible in this situation. – Wain Apr 14 '14 at 17:41
  • So how do I get the same data that is printed in the NSLog to NSString? – Andrew Sheridan Apr 14 '14 at 17:49