2015-10-05 58 views
0

我在Cloud9中创建了一个在线PHP页面,我可以连接到MySQL数据库并执行任何我想要的操作。我可以在不使用AFNetworking的情况下从我的iOS应用程序模拟器连接该页面。不过,我应该使用这个库并创建一个POST请求。 我POST请求失败,并给出了此错误:iOS - 连接PHP时AFNetworking失败页面

Error : Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}

我的Objective-C代码为:

NSString *url = [URLFactory targetURL]; 
NSDictionary *dictionary = @{ 
          @"key" : @"value", 
          }; 

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; 

[manager POST:url parameters:dictionary success:^(AFHTTPRequestOperation *operation, id responseObject) 
{ 
    NSLog(@"Response : %@",responseObject); 
} failure:^(AFHTTPRequestOperation *operation, NSError *error) { 

    NSLog(@"Here!"); 

    NSLog(@"Error : %@",error); 
}]; 

和PHP:

<?php 
header('Content-type: application/json'); 
$isPostRequest = $_SERVER['REQUEST_METHOD'] == 'POST'; 

if ($isPostRequest) { 

    echo json_encode("done!"); 
} 
?> 

正如你所看到的,我不是做任何事情。我会检查参数,但现在我只想连接。我看到“这里!”记录并获取错误。我做错了什么或者有什么缺失?我发现了一些关于这个错误的帖子,但他们并没有失败。因此我很困惑。

谢谢!

回答

0

试着改变你的代码,使一个数组,像这样:

echo json_encode(array("response" => "done!")); 

然后在你的iOS代码,得到响应对象:

NSArray *jsonObjects = [responseObject objectForKey:@"response"]; 
+0

非常感谢!我认为我的错误是关于Objective-c的,但是你的解决方案起作用了:)再次,谢谢你! – anyName

+0

没问题,乐意帮忙,接受答案关闭它。祝你好运! – dstudeba