Getting data out of the NSURLResponse completion block

前端 未结 3 682
情深已故
情深已故 2020-12-24 09:54

It looks like I didn\'t get the concept of blocks completely yet...

In my code I have to get out the JSON data from the asychronous block to be retur

3条回答
  •  佛祖请我去吃肉
    2020-12-24 10:08

    First, to answer your question:

    But for some reason returned json object is nil. I wonder why?

    The variable that you are returning has not been set at the time when you return it. You cannot harvest the results immediately after the sendAsynchronousRequest:queue:completionHandler: method has returned: the call has to finish the roundtrip before calling back your block and setting json variable.

    Now a quick note on what to do about it: your method is attempting to convert an asynchronous call into a synchronous one. Try to keep it asynchronous if you can. Rather than expecting a method that returns a NSMutableDictionary*, make a method that takes a block of its own, and pass the dictionary to that block when the sendAsynchronousRequest: method completes:

    - (void)executeRequestUrlString:(NSString *)urlString withBlock:(void (^)(NSDictionary *jsonData))block {
        // Prepare for the call
        ...
        // Make the call
        [NSURLConnection sendAsynchronousRequest:request
                                        queue:[NSOperationQueue currentQueue]
                            completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
            NSLog(@"dataAsString %@", [NSString stringWithUTF8String:[data bytes]]);
            NSError *error1;
            NSMutableDictionary * innerJson = [NSJSONSerialization
                JSONObjectWithData:data options:kNilOptions error:&error1
            ];
            block(innerJson); // Call back the block passed into your method
            }];
    
    }
    

提交回复
热议问题