在我的应用程序在MYSql数据库中插入记录后,我想捕获新记录的ID并将其发送回应用程序以进行同步。
问题是如何有效地捕获它并将其发送回应用程序。
以下是发布到服务器的代码。
-(void) postToServer: (NSString *) jsonString {
NSURL *url = [NSURL URLWithString:@"http://www.~.com/services/new.php"];
NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:url];
[rq setHTTPMethod:@"POST"];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
// NSData *jsonData = [@"{ \"item\": \"hat\" }" dataUsingEncoding:NSUTF8StringEncoding];
[rq setHTTPBody:jsonData];
[rq setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[rq setValue:[NSString stringWithFormat:@"%ld", (long)[jsonData length]] forHTTPHeaderField:@"Content-Length"];
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *data, NSError *err) {
NSLog(@"POST sent!");
NSLog(@"Error%@",err);
}];
}
这是我设置为回显插入ID的php。
$newid = mysql_insert_id();
echo $newid;
但是,如何让此网络服务将信息发送回应用程序?
感谢您的任何建议。
答案 0 :(得分:0)
只需在PHP中回显JSON响应(错误/数据),然后您的AsynchronousRequest将回复给您:
[NSURLConnection sendAsynchronousRequest:rq queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *rsp, NSData *data, NSError *err) {
NSLog(@"POST sent!");
if (err) {
NSLog(@"Error%@",err);
} else {
NSDictionary *jsonResults = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
NSLog(@"Results: %@", jsonResults);
// NSString *insertID = jsonResults[@"insert_id"];
}
}];
PHP:
// Set the response type as JSON
header("Content-Type: application/json");
...
if ($sqlResult) {
// Return your insertID here
$response = array("insert_id" => $sqlResult['insert_id']); // example
exitWithResponse($response);
} else {
exitWithHttpCode(400, "Bad Request"); // example
}
...
# Exit with response
function exitWithResponse($response) {
$status = array('code' => '200', 'response' => $response, 'error' => NULL);
echo json_encode($status);
http_response_code(200);
exit();
}
# Exit with error code
function exitWithHttpCode($code, $error) {
$status = array('code' => $code, 'response' => NULL, 'error' => $error);
echo json_encode($status);
http_response_code($code);
exit();
}
有关状态代码的更多信息:http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html