IOS/PHP:写入服务器数据库后,在应用程序中捕获成功消息


IOS/PHP: Capture success message in app after writing to server database

当我的应用程序在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;

然而,我如何让这个网络服务将信息发送回应用程序?

谢谢你的建议。

只需在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

相关文章: