无法通过 NSURLRequest 正确发布 NSData


Can't post NSData properly via NSURLRequest

我正在创建一个食谱应用程序,该应用程序需要访问食谱的在线数据库。

目前,我无法接收另一端的数据。但是,我已经验证了NSURLRequest是否登陆了正确的页面。

以下是请求代码:

______.m 文件

NSURL *URL = [NSURL URLWithString:@"http://localhost/"];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
request = [NSMutableURLRequest requestWithURL:URL
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSURLConnection *connection= [[NSURLConnection alloc] initWithRequest:request delegate:self];
// store recipe
NSString *path = [[NSBundle mainBundle] pathForResource:@"Recipes" ofType:@"plist"];
NSMutableDictionary *dictionaryOfRecipes = [[NSMutableDictionary alloc] initWithContentsOfFile:path];
NSMutableArray *arrayOfRecipes = [dictionaryOfRecipes objectForKey:@"recipesArray"];
NSData *data = [[NSData alloc] init];
data = [arrayOfRecipes objectAtIndex:self.thisRecipeIndex];
// post data
[request setHTTPBody:data];
[connection start];

打印出正在发送的数据 (NSData *) $2 = 0x09071f40 { ingredients = ( "penne pasta", water ); instructions = ( "put the penne in the water", boil ); recipeName = Penne; }

_____.php文件

<?php
// initialize connection to database
$db = mysql_connect('localhost', 'xxxxxxx', 'xxxxxxx');
$db_name = "project3";
mysql_select_db($db_name, $db);
// store incoming data as php variables
error_log(print_r($_POST, true));
$recipeName = $_POST['recipeName'];
// create mysql query
$query = "INSERT INTO recipeNamesTable (recipeName) VALUES '$recipeName'";
mysql_query($query);
mysql_close($db);
?>

我对潜在的问题有一些猜测,但不确定我是否正确。虽然[arrayOfRecipes objectAtIndex:self.thisRecipeIndex]是一个NSDictionary,但我将其存储为NSData,尽管这不会返回任何错误,所以我保持这种方式。我是否需要将其存储为NSDictionary,然后将其转换为NSData?如果这不是问题所在,我很想得到一些关于上面其他问题的反馈。

正如你似乎已经猜到的那样,这两行:

NSData *data = [[NSData alloc] init];
data = [arrayOfRecipes objectAtIndex:self.thisRecipeIndex];

不要按照你的想法去做。 第一行分配一个新的空NSData对象,并将指向该对象的指针存储在 data 变量中。 第二行从数组中检索NSDictionary,并将指向该数组的指针放在 data 变量中。 现在,您已经忘记了data过去指向的空NSData对象。 此外,您已将错误类型的指针存储到 data 变量中。 该变量应该包含指向NSData的指针,但您已在其中放置了指向NSDictionary的指针。 编译器没有抱怨,因为-[NSArray objectAtIndex:]返回了一个完全通用的对象指针id。 编译器无法知道实际检索到的对象类型。

因此,是的,您需要确定用于将字典中的信息传达到服务器的通信协议和数据交换格式。 然后,您需要将字典转换为该格式并发送结果数据。 您可能会查看NSJSONSerialization.