【发布时间】:2014-10-09 08:25:44
【问题描述】:
目标 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 中。它能够保存。 我尝试记录我的响应状态代码,它显示为“0”。有人可以帮我解决这个问题吗?
【问题讨论】:
-
你是否错过了连接:NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self]; ?
标签: ios objective-c iphone json rest