Reputation: 1238
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]
Upvotes: 0
Views: 2761
Reputation:
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 !
Upvotes: 3