簡體   English   中英

我究竟做錯了什么? 嘗試存儲設備令牌

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM