AFNetworking - 当PHP打印时,iOS获取JSON

时间:2022-05-02 06:59:46

I have just started using AFNetworking, but I can't seem to figure out how to get the following to work.

我刚刚开始使用AFNetworking,但我似乎无法弄清楚如何让以下工作。

My URL points to a PHP file which has printed out data it retrieved from a database as JSON, but with AFNetworking I get the "Expected Content Type" error.

我的URL指向一个PHP文件,该文件将从数据库中检索的数据打印为JSON,但是使用AFNetworking我收到“预期内容类型”错误。

My code is the following but with a different URL.

我的代码如下,但使用不同的URL。

NSURL *url = [NSURL URLWithString:@"http://www.example.com/json.php"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];

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

[operation start];

2 个解决方案

#1


5  

I figured it out! :D

我想到了! :d

<?php header("Content-type: text/json"); ?>

Put this at the top of your page before anything is printed on the screen and AFNetworking will recognise it as JSON

在屏幕上打印任何内容之前将其放在页面顶部,AFNetworking会将其识别为JSON

#2


2  

@Ashley Thanks for sharing this. I had the same problem and this resolved it. However it should be

@Ashley感谢分享这个。我有同样的问题,这解决了它。不过它应该是

header("Content-type: application/json"); 

and not as you state

而不是你说的

#1


5  

I figured it out! :D

我想到了! :d

<?php header("Content-type: text/json"); ?>

Put this at the top of your page before anything is printed on the screen and AFNetworking will recognise it as JSON

在屏幕上打印任何内容之前将其放在页面顶部,AFNetworking会将其识别为JSON

#2


2  

@Ashley Thanks for sharing this. I had the same problem and this resolved it. However it should be

@Ashley感谢分享这个。我有同样的问题,这解决了它。不过它应该是

header("Content-type: application/json"); 

and not as you state

而不是你说的