0

I'm getting data from quizlet.com and it works OK for simple code:

-(void) grabbQuizletWithUrl:(NSURL*)requstURL {

     NSString *dataString = [NSString stringWithContentsOfURL:requestURL encoding:NSUTF8StringEncoding error:&error]; 

     NSDictionary *dict = [dataString JSONValue];
}

But I need to use NSURLConnection to start and stop activity indicator. I'm trying

-(void) grabbQuizletWithUrl:(NSURL*)requstURL {

    NSURLRequest *quizletRequest = [[NSURLRequest alloc] initWithURL:requestURL];
    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:quizletRequest
                                                          delegate:self];
    [connection release];
    [quizletRequest release];

}

// and getting data in delegate method:



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [self.activityIndicator stopAnimating];

    NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

    NSDictionary *dict = [dataString JSONValue];

}

I'm getting messages like these:

[2377:707] -JSONValue failed. Error is: Unexpected end of input

[2377:707] -JSONValue failed. Error is: Illegal start of token [.]

[2377:707] -JSONValue failed. Error is: Illegal start of token [d]

Michael
  • 1,238
  • 2
  • 15
  • 26

1 Answers1

3

In - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;, you should just append the recieved data to the previously stored, as you only got just a part of the response, ie :

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // someNSMutableDataIVar is an ivar to store the data in
    [someNSMutableDataIVar appendData:data];
}

then in another delegate method called :- (void)connectionDidFinishLoading:(NSURLConnection *)connection; you should process the data.

-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // the connection finished loading all data, process...
    [self.activityIndicator stopAnimating];
    NSString *dataString = [[NSString alloc] 
                            initWithData:someNSMutableDataIVar
                                encoding:NSUTF8StringEncoding];
    NSDictionary *dict = [dataString JSONValue];
}

The asynchronous URL loading system is described in detail in the URL Loading System Programming Guide from Apple.

Hope this helps !

  • Thank you, that's what I missed! Now it works. I did not learn that Apple's guide but just glanced over it. – Michael Jul 16 '11 at 05:48