通过http请求发送设备令牌

时间:2012-07-09 23:55:41

标签: iphone ios push-notification

我可以获取iPad的设备令牌,但问题是如何通过php代码将其发送到服务器中的数据库。

我测试了php代码并且它正在运行。

这是我发送设备令牌的功能:

-(void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken{

NSString *devToken = [[[[deviceToken description] 
                        stringByReplacingOccurrencesOfString:@"<"withString:@""] 
                       stringByReplacingOccurrencesOfString:@">" withString:@""] 
                      stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"%@",devToken);
NSString *sli = [NSString stringWithFormat:@"http://localhost:8888/insertiphone.php?number=%@",devToken];
NSURL *url = [NSURL URLWithString:sli];

NSData *test = [NSData dataWithContentsOfURL:url];
if ([test length] == 0) {
    NSLog(@"no done");
}

}

它不起作用..

这是php代码:

<?php
function inserttodatabase(){
$con = mysql_connect("localhost","root","root");
mysql_select_db("my_db", $con);
mysql_query("INSERT INTO iphoneid (idip)
VALUES ($_GET[number])");
echo "done";
}

inserttodatabase(); 
?>

更新了,我也试过这些代码但没有工作

 NSString *devToken = [[[[deviceToken description] 
                        stringByReplacingOccurrencesOfString:@"<"withString:@""] 
                       stringByReplacingOccurrencesOfString:@">" withString:@""] 
                      stringByReplacingOccurrencesOfString: @" " withString: @""];

NSString *sli = [NSString stringWithFormat:@"http://localhost:8888/insertiphone.php?      number=%@",devToken];
NSLog(@"%@",sli);
NSURL *url = [NSURL URLWithString:sli];

NSURLRequest *urlr = [NSURLRequest requestWithURL:url     cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10.0];

NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:urlr     delegate:self];

if (connection){
    NSLog(@"connecting");
}else {
    NSLog(@"error");
}

它表示连接但没有任何内容会插入到数据库中

2 个答案:

答案 0 :(得分:0)

检查nil(dataWithContentsOfUrl可以在问题上返回nil)

使用NSURLConnection(connection:didFailWithError :)或ASIHttpRequest(requestFailed :)发送请求,您将获得更好的错误信息和控制权。

rest web services in iphone

http://allseeing-i.com/ASIHTTPRequest/How-to-use

此外,在从iPhone客户端发出请求时,服务器代码是否执行?调试或跟踪服务器代码,以便更好地了解正在发生的事情。

您还可以设置类似charles proxy之类的内容,以查看线路上的内容以及即将发生的内容。

这是一篇博客文章调试与charles代理的连接问题。 http://blog.mediarain.com/2009/08/iphone-http-connection-debugging/

最后,作为一次性尝试[machinename] .local:8888 ...如果您有名称解析,本地主机解析问题等问题。

答案 1 :(得分:0)

首先,提供有关服务代码正在执行的操作以及测试方式的更多信息。您编写的代码是发出HTTP GET请求而不是put或post。在大多数情况下,将记录插入数据库的Web服务(由URL中的“insertiphone.php”证明)将使用HTTP POST而不是GET实现。如果您使用GET发送它,正如您所做的那样,它将无法按预期执行。因此,提供有关您如何了解服务器工作情况的更多信息以及您测试服务器所做的工作将有助于诊断您的问题。

假设您已经检查了服务并且验证了它正在期待HTTP GET(如果数据正在服务上更新,那么不是很好的RESTful设计,但肯定可能),那么我会同意@bryanmac提供的答案。查看他的链接,了解更好的HTTP请求方法,检查服务器端以查看请求是否通过,使用CharlesProxy进行调试等等。

如果您的服务需要GET,我可以提供另一个调试提示,您可以使用Web浏览器对其进行测试,在启用了开发人员扩展的Safari中尝试使用它,并使用它来监视资源请求和响应。这将允许您查看成功的请求是什么样的,可以将您与使用CharlesProxy可以看到的实际请求进行比较。