[英]What am I doing wrong? Trying to store device token
好的,我已经设法弄清楚了大约三个星期,而且我认为我不需要再剃光头了!!! 我已经尽可能地解构了代码,因此我可以专注于仅将设备令牌获取到我的数据库中。 当我运行代码时,我在数据库中获得了一个时间戳记录,就是这样,所以我知道它已连接,但那里什么也没有。
这是我的代码
- (void)application:(UIApplication*)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken {
NSString *tokenStr = [deviceToken description];
NSString *pushToken = [[[[tokenStr
stringByReplacingOccurrencesOfString:@"<" withString:@""]
stringByReplacingOccurrencesOfString:@">" withString:@""]
stringByReplacingOccurrencesOfString:@" " withString:@""] retain];
// Save the token to server
NSString *urlStr = [NSString stringWithFormat:ServerApiURL];
NSURL *url = [NSURL URLWithString:urlStr];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req setHTTPMethod:@"POST"];
[req setValue:@"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:@"Content-Type"];
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"&token=%@",
pushToken] dataUsingEncoding:NSUTF8StringEncoding]];
[req setHTTPBody:postBody];
[[NSURLConnection alloc] initWithRequest:req delegate:nil];
NSLog(@"%@", pushToken);
NSLog(@"%@", url);
}
这是非常简单的PHP
// initialize connection to database
$db = mysql_connect('localhost', 'xxxxxxxxx', 'xxxxxxxx');
$db_name = "xxxxxxxxxxxx";
mysql_select_db($db_name, $db);
// store incoming data as php variables
error_log(print_r($_POST, true));
$token = $_POST['token'];
// create mysql query
mysql_query("INSERT INTO iPhone (device_token)
VALUES ('$token')");
mysql_query($query);
mysql_close($db);
?>
我在数据库中得到的是时间戳,但在device_token下什么也没有。 我将不胜感激。 谢谢。
是否NSLog(@"%@", pushToken);
有想要提交的有效令牌吗?
另外,您可以尝试将$ _POST转储到PHP页面上以查看其收到的内容。
另外,在使用mysqlrealescapestring();
将输入插入数据库之前,请确保对PHP页面上的输入进行清理mysqlrealescapestring();
或考虑使用PDO,因为现在不鼓励使用旧的mysql函数。 PDO也会自动清理输入。
以下是有关PDO的更多信息:
http://us2.php.net/manual/zh/ref.pdo-mysql.php
http://us2.php.net/manual/zh/pdo.query.php
编辑:
这可能是问题的原因。 更换
NSMutableData *postBody = [NSMutableData data]; [postBody appendData:[[NSString stringWithFormat:@"&token=%@", pushToken] dataUsingEncoding:NSUTF8StringEncoding]];
与
NSData *postBody = [[NSString stringWithFormat:@"&token=%@", pushToken] dataUsingEncoding:NSUTF8StringEncoding];
唯一的区别是NSData而不是NSMutableData以及更直接的设置方法。 我不确定这是否是问题的根源,但是尝试一下不会很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.