为什么我从此请求iOS JSON获得空响应

时间:2014-10-09 08:25:44

标签: ios objective-c iphone json rest

目标C代码

@try {
        NSURL *postURL = [NSURL URLWithString: @"http://yyy.com/api/Customer/"];
        NSDictionary *myDic = [[NSDictionary alloc] initWithObjectsAndKeys:
                               self.firstNameTextField.text, CustFirstName,
                               self.lastNameTextField.text, CustLastName,
                               nil];

        NSError *error;

        NSData *jsonData = [NSJSONSerialization dataWithJSONObject:myDic options:NSJSONWritingPrettyPrinted error:&error];

        if (!jsonData) {
            NSLog(@"Got an error: %@", error);
        } else {

            // Get our Access Token back
            NSString *savedToken = [[NSUserDefaults standardUserDefaults]
                                    stringForKey:@"savedToken"];
            NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
            [request setURL:postURL];
            [request setHTTPMethod: @"POST"];
            [request setValue: @"application/json" forHTTPHeaderField: @"Accept"];
            [request setValue: @"application/json; charset=utf-8" forHTTPHeaderField: @"content-type"];
            [request setValue:savedToken forHTTPHeaderField:@"Authorization"];
            [request setHTTPBody:jsonData];

            NSHTTPURLResponse *response = nil;

            NSLog(@"Response code: %ld", (long)[response statusCode]);

            //NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
            if ([response statusCode] >= 200 && [response statusCode] < 300)
            {
                NSLog(@"Saving Success!");
                [self performSegueWithIdentifier:@"edit_add_customer" sender:self];
            } else {
                NSLog(@"Saving Fail!");
                [self alertStatus:@"Please try again" :@"Saving Fail" :0];
            }


        }
}
@catch (NSException *exception) {
    NSLog(@"Exception: %@", exception);
    [self alertStatus:@"Error Retrieving Customer Data." :@"Error!" :0];
}

无论如何,我的JSON字符串是正确的,因为我放在我的Rest Client中。它能够保存。 我尝试记录我的响应StatusCode,它显示为&#39; 0&#39;。有人可以帮我这个吗?

1 个答案:

答案 0 :(得分:0)

在执行实际请求之前,您需要获取statusCode

  NSLog(@"Response code: %ld", (long)[response statusCode]);
  NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

你必须在请求后检查statusCode

  NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
  NSLog(@"Response code: %ld", (long)[response statusCode]);