Search code examples
phpobjective-cjsonasynchronousnsurlconnection

Get no data from NSURLRequest (asynchronous) from php/json service


I'm having a problem retrieving data from a website to iOS device. The web uses php file to read some data from mySQL database. Then it sends back data in json format.

I'm using the following code to receive the data. The code is put into viewDidLoad. To avoid the UI related code from executing without waiting for the web response, I'm putting the NSURLRequest/NSURLConnection operations into an asynchronous queue with GCD. Still, the console window displays the NSLog that the self.connectionData has no data.

This result is the same as I put the NSURLRequest/NSURLConnection operations into the viewDidLoad function directly. Do you know what's wrong here, and why I can't get the data?

When I run the php directly from browser, the web service runs fine.

Thank you very much!

Regards, Paul

- (void)viewDidLoad {   
[super viewDidLoad];

dispatch_queue_t concurrentQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
dispatch_async(concurrentQueue, ^{

    dispatch_sync(concurrentQueue, ^{

        NSString *urlAsString = @"http://www.myexamplesite.com/loadProgram.php";
        NSURL *url=[NSURL URLWithString:urlAsString];


        NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url
                                                    cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30.0F];
        NSOperationQueue *queue = [[NSOperationQueue alloc] init];
        [NSURLConnection sendAsynchronousRequest:urlRequest queue: queue
                               completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
                                   if ([data length]>0 && connectionError == nil) {
                                       [self.connectionData appendData:data];
                                       NSLog(@"datalength is %ld", [self.connectionData length]);
                                       NSString *retString = [[NSString alloc] initWithData:self.connectionData encoding:NSUTF8StringEncoding];
                                       NSLog(@"json returned: %@ <end>", retString);
                                   }

                                   else if ([data length]==0 && connectionError ==nil)
                                   {NSLog(@"Nothing was downloaded!");
                                   }
                                   else if (connectionError != nil){
                                       NSLog(@"Error happend = %@", connectionError);
                                   }
                               }];

    });

});

}

Solution

  • You do not initialize self.connectionData. So, you need the following piece at the beginning:

    if (!self.connectionData) {
        self.connectionData = [[NSMutableData alloc] init];
    }