应该在NSURLConnection之前调用connectionDidFinishLoading吗?

时间:2014-06-27 20:42:56

标签: ios iphone objective-c json

我正在开发一个触发一些NSURL请求的iOS应用程序。我创建了一个实现didReceiveData的WebService类,如下所示:

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    // Append the new data to the instance variable you declared
    [_responseData appendData:data];
}

其中_responseData是NSMutableData *属性。然后我创建了几个子类来创建他们的特定请求并实现connectionDidFinishLoading。具体来说,我有一个RegisterService类,它实现如下:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    // The request is complete and data has been received
    // You can parse the stuff in your instance variable now
    NSError *error = nil;
    _parsedData = [NSJSONSerialization JSONObjectWithData:_responseData options:kNilOptions error:&error];
    NSLog(@"register data: %@",_parsedData);
    registerAnswer serverAnswer = [[_parsedData objectForKey:@"success"] integerValue];

    if (serverAnswer == REGISTER_SUCCESS) {
        // Give data to delegate to handle
        [self.delegate successRegister];
    }
    else { // serverAnswer == REGISTER_FAIL
        NSLog(@"register message: %@",[[_parsedData objectForKey:@"message"] stringValue]);
        [self.delegate failedRegister];
    }
}

我有2个使用此服务的不同视图控制器。其中一个人称之为:

self.personRegistering.username = self.txtUsername.text;
self.personRegistering.password = self.txtPassword.text;
if (self.personRegistering.isCustomer) {
    // register customer
    DGRegisterService* myRegisterService = [[DGRegisterService alloc] initWithDelegate:self];
    [myRegisterService registerPerson:self.personRegistering];
}
else {
    // continue to get picture
    [self performSegueWithIdentifier:@"RegisterPageThreeToFour" sender:self];
}

它完美无缺。另一个(第4页)让用户在注册之前拍照。这是代码:

- (IBAction)btnTakePicture:(id)sender {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        // Camera is available
        UIImagePickerController* myCamera = [[UIImagePickerController alloc] init];
        myCamera.sourceType = UIImagePickerControllerSourceTypeCamera;
        myCamera.delegate = self;
        [self presentViewController:myCamera animated:YES completion:NULL];
    }
}

#pragma mark - UIImagePicker Delegate

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    [picker dismissViewControllerAnimated:YES completion:NULL];
    // Register person first
    DGRegisterService* myRegisterService = [[DGRegisterService alloc] initWithDelegate:self];
    [myRegisterService registerPerson:self.personRegistering];

//    // Now send pic
//    UIImage* picture = [info objectForKey:UIImagePickerControllerOriginalImage];
//    DGUploadService* myUploadService = [[DGUploadService alloc]     initWithDelegate:self];
//    [myUploadService uploadImage:picture forUsername:self.personRegistering.username];
}

现在,第二个发送请求,服务器正确处理它,发回这个JSON对象:

{"success":1,"message":"Account successfully created."}

这是我的预期。但是,两个NSLog语句都显示“(null)”。有时,应用程序崩溃,因为objectForKey被发送到不响应它的实例。在其他时候,控制台将在我在XCode上点击“停止”后显示JSON对象。其余时间它不会崩溃或显示对象。

由于此页面使用相机,我必须只在iPhone上测试,而不是模拟器。另一个页面在模拟器和iPhone中每次都正确显示JSON对象。我正在使用的iPhone是iOS7.1.1的4S。

2 个答案:

答案 0 :(得分:1)

如果您的意思是以下行中的NSLog

NSError *error = nil;
_parsedData = [NSJSONSerialization JSONObjectWithData:_responseData options:kNilOptions error:&error];
NSLog(@"register data: %@",_parsedData);

有时打印"(null)",这可能是由JSONObjectWithData调用中的错误引起的。

我建议添加

NSLog(@"received data: %@", _responseData);

检查数据是否正常,

NSLog(@"register data: %@ -- (error: %@)",_parsedData, [error localizedDescription]);

查看是否返回了错误。

答案 1 :(得分:0)

此代码没有任何问题。根据塞尔吉奥的建议,我NSLog了收到的数据和错误。 JSON解析失败,打印原始数据显示服务器端的php脚本正在发送带有JSON对象的错误消息,导致无法正确解析。我们修复了php文件,现在就可以了。