2013-06-30 37 views
1

我试图启动这个操作,它甚至没有进入NSLOG。 我想它与我的stringUrl的东西,也许它不会像这样工作?AFNetworking JSON请求不起作用

这是我的代码:

NSString *stringUrl = [[NSString alloc]initWithFormat:@"http://example.com/add_user.php?username=%@&password=%@&country=%@&email=%@",[self.usernameTextField text],[self.passwordTextField text], countrySelected, [self.emailTextField text]]; 

NSURL *url = [NSURL URLWithString:stringUrl]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) { 
    NSDictionary *dict = JSON; 
    NSLog(@"IP Address: %@", [JSON valueForKeyPath:@"item"]); 
} failure:nil]; 

[operation start]; 

编辑: 这是我从失败中得到了块:

错误域= AFNetworkingErrorDomain代码= -1016“预期的内容类型{( “text/json”, “application/json”, “text/javascript” )},got text/html“UserInfo = 0xa2b4300 {NSLocalizedRecoverySuggestion = {”type“:”1“,”item“:”User added成功“。”} ,AFNetworkingOperationFailingURLRequestErrorKey = HTTP://EXAMPLE.com/add_user.php用户名= aaasafasfasf &密码= AAA &国家安哥拉=电子邮件& = aaaasfasfasfasfasf>,NSErrorFailingURLKey = http://EXAMPLE.com/add_user.php?username=aaasafasfasf&password=aaa&country=Angola&email=aaaasfasfasfasfasf,NSLocalizedDescription =预期的内容类型{( “文/ JSON” , “应用/ JSON”, “文/ JavaScript的” )},得到的text/html,AFNetworkingOperationFailingURLResponseErrorKey =}

+0

使用NSLog获取stringUrl的值并粘贴到浏览器中,然后查看结果。 – edzio27

+0

@ edzio27这就是我得到的: {“type”:“0”,“item”:“用户名已存在电子邮件已存在”} 它是我想得到但它甚至没有得到NSLog –

+0

可能你尝试使用失败块? –

回答

4

为了进入AFJSONRequestOperation的成功块,你还需要坚持服务器发送的正确内容类型。目前您的服务器正在返回text/html内容类型作为响应,因此它会进入失败区域。

作为故障块消息表明,改变内容类型回是文本/ JSON应用/ JSON因为正在使用的AFJSONRequestOperation。

对于PHP,您可以更改在这个问题下面的答案返回的内容类型:How to change content type in php?

你可以只添加以下现有的标题行的另一行:

header('Content-Type: text/json'); 

无需替换现有标题行,除非有标题行将内容类型设置为文本/ json应用程序/ json以外的其他内容。

+0

非常感谢我的朋友,它的工作:) –

+0

现在我有另一个问题: 错误域= NSCocoaErrorDomain代码= 3840“该操作不能完成。(可可错误3840)”的UserInfo = 0xa361a40(围绕字符45.转义控制字符){NSDebugDescription =未逸出控制字符周围字符45.} 我想NSURL太长了。 –

+1

@RotemShukron你将需要检查返回的JSON是否是有效的JSON。你可以尝试在这里找到的建议:http://stackoverflow.com/questions/6966349/json-parse-error –