0

我在 sqlite 中存储 id、lat、lng 和时间戳,现在需要将其以 JSON 对象的形式发送到服务器。

这是我插入数据的地方。

NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO location (latitude, longitude, timeStamp) VALUES (%g, %g, %@)",newLocation.coordinate.latitude, newLocation.coordinate.longitude, newLocation.timestamp];    
char *error;   
if ( sqlite3_exec(databasehandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)
{
    NSLog(@"Location inserted. %@", newLocation.timestamp);
}    

else NSLog(@"Error: %s", error);

这是我现在正在处理的代码。我不知道从这里去哪里:

 NSString *queryStatement = [NSString stringWithFormat:@"SELECT ID, latitude, longitude, timeStamp FROM LOCATION"];

// Prepare the query for execution
sqlite3_stmt *statement;


if (sqlite3_prepare_v2(databasehandle, [queryStatement UTF8String], -1, &statement, NULL) == SQLITE_OK)
{
    // Iterate over all returned rows
    while (sqlite3_step(statement) == SQLITE_ROW) {

这是我想用来发送数据的 JSON/HTTP 代码

responseData = [NSMutableData data];

//whatever your server address is
NSURL *url = [NSURL URLWithString:@"http://www.resturl.com/whatever"];

NSError *jsonError;
//NSJSONSerialization is Apple's new json serialization class so we can use it to convert to and from json and foundation objects
NSData *requestdata = [NSJSONSerialization dataWithJSONObject:returnArray options:0 error:&jsonError];

NSMutableURLRequest *request;
 request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestdata]; 

//this kicks off the request asynchronously
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

任何帮助,将不胜感激!

4

1 回答 1

1

我正在使用相同的代码,但没有使用 web 服务在数据库中发布数据。

NSURL *url = [NSURL URLWithString:@"someurl/try_ws_iphone/insertRecords.php"];
NSArray *res=[[NSArray alloc] initWithObjects:txtname.text, nil];
NSError *jsonError;
//NSJSONSerialization is Apple's new json serialization class so we can use it to convert to and from json and foundation objects
NSData *requestdata = [NSJSONSerialization dataWithJSONObject:res options:0 error:&jsonError];


NSMutableURLRequest *request;
request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:[NSString stringWithFormat:@"%d", [requestdata length]] forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:requestdata];

//this kicks off the request asynchronously
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
于 2013-04-19T04:10:55.023 回答