在iOS模拟器上工作的HTTP GET请求在iPhone设备上无法工作

3
我的应用正在调用一个基本的PHP脚本,输出JSON数据。
我是这样调用我的PHP脚本的:
NSString *buildURL = [NSString stringWithFormat: @"http://xxxx.com/api.php?action=authenticate_user&email=%@&password=%@&deviceToken=%@", _emailAddress, _password, deviceToken];
NSURL *url = [NSURL URLWithString: buildURL];
NSData *data = [NSData dataWithContentsOfURL:url];
NSString *ret = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

// Parse the result
NSString *ret2 = [ret stringByReplacingOccurrencesOfString:@"null" withString:@""];
NSError* error;
NSDictionary *JSON =
[NSJSONSerialization JSONObjectWithData: [ret2 dataUsingEncoding:NSUTF8StringEncoding]
                                options: NSJSONReadingMutableContainers
                                  error: &error];

NSString* status = [JSON objectForKey:@"status"];
NSString* email = [JSON objectForKey:@"email"];
NSString* userID = [JSON objectForKey:@"userID"];
NSString* agentID = [JSON objectForKey:@"agentID"];
NSString* picture = [JSON objectForKey:@"picture"];

在我的 iPhone 上运行此代码时,出现所有变量均为 (null) 的情况,但在模拟器上可以获得正确的数据。

我的 PHP 脚本输出如下:

{"status":"1", "agentName":"Bill", "picture":"http://xxxx.com/thumb_ad1-8908968097.jpg", "departmentName":"", "email":"test@gmail.com", "agentID":"513", "userID":"3"}null

有什么想法我做错了什么吗?

你的PHP脚本输出末尾为什么会有一个“null”位? - Shaggy Frog
这是 PHP 脚本输出的,但我认为这并不重要,因为它在模拟器中运行正常。 - Alosyius
1
一个好的经验法则是:不要假设仅因为某个东西在模拟器中运行良好,它就一定能在设备上运行。你应该先修复那个问题,因为那不是有效的 JSON。 - Shaggy Frog
2
添加一些NSLog语句,使用Xcode调试器。 - zaph
1
首先,使用NSLog记录错误。此外,“deviceToken”作为最后一个参数似乎是模拟器和设备之间最可能的区别。最后,一旦您使其正常工作,请考虑使用异步请求。 - danh
代理请求和响应。展示实际使用 statusemail 等变量的代码。 - Carl Veazey
1个回答

2

我猜测您的网络服务没有启动(将您的网络服务从本地服务器转移到全球服务器)。

您当前的 PHP 服务器与设备未连接,在模拟器中可以输出,因为 Mac OS 已与服务器连接。


谢谢,它在我的情况下起作用了。我不知道iOS不支持重定向。 - Anil Ravsaheb Ghodake

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接