SBJson和NSData

时间:2011-07-15 21:13:10

标签: objective-c ios nsdata sbjson

我从quizlet.com获取数据,它可以用于简单的代码:

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

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

     NSDictionary *dict = [dataString JSONValue];
}

但是我需要使用NSURLConnection来启动和停止活动指示器。我正在尝试

-(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];

}

我收到的消息如下:

[2377:707] -JSONValue失败。错误是:意外的输入结束

[2377:707] -JSONValue失败。错误是:非法启动令牌[。]

[2377:707] -JSONValue失败。错误是:非法启动令牌[d]

1 个答案:

答案 0 :(得分:3)

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;中,您只需将收到的数据附加到先前存储的数据中,因为您只获得了响应的一部分,即:

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

然后在另一个名为- (void)connectionDidFinishLoading:(NSURLConnection *)connection;的委托方法中,您应该处理数据。

-(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];
}

异步URL加载系统在Apple的URL Loading System Programming Guide中有详细介绍。

希望这有帮助!