php - 无法通过 NSURLRequest 正确发布 NSData

标签 php objective-c ios xcode 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 { 成分=( “意大利管面”, 水 ); 说明 = ( “将通心粉放入水中”, 熬 ); 食谱名称=通心粉;

_____.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,这是一个完全通用的对象指针。编译器无法知道实际检索到的是哪种对象。

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

关于php - 无法通过 NSURLRequest 正确发布 NSData,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10378343/

相关文章:

php - MySQL 上删除级联删除parent_id on pk_id 删除

php - 在 Apache/Windows 2008 上使用 PHP 和 Oracle 时身份验证登录页面无法正常工作

ios - setImage forState 方法为按钮上的所有状态设置图像

ios - 如何在dispatch_async iOS Swift 2.0 中中断队列进程

适用于 Android、iOS 和 BB 的 ASP.NET Web 服务

php - Aramex 汇率计算器 APT 返回错误代码 "ISE01"

php - Laravel 4 - 过滤结果和缓存

ios - 在 GMSMapView 中检测平移手势

objective-c - NSData initWithContentsOfURL : does not return the original allocation?

iOS CPU_FATAL 0% 在后台