简体   繁体   English

在iOS应用程序中返回JSON

[英]Return JSON in iOS application

I'm trying to return a simple JSON in my iOS app through PHP file. 我正在尝试通过PHP文件在我的iOS应用中返回一个简单的JSON。

PHP: PHP:

<?php
header('Content-Type: application/json');
$myarray = array("io" => 1, "tu" => 2);
$out = json_encode($myarray);

echo $out;

?>

iOS: iOS版:

-(void)provePHP{

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://mysite/myphpfile.php"]];
    [request setValue:@"application/json" forHTTPHeaderField:@"Accept"];
    [request setValue:@"application/json"forHTTPHeaderField:@"Content-Type"];

    NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection
    didReceiveData:(NSData *)data{

    NSError *error;

    NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &error];

    NSLog(@"%@ - %@", jsonDict, error);

}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

    NSLog(@"FINISH");
}

- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error{

    NSLog(@"Error");
}

I don't understand what I do wrong. 我不明白我做错了什么。 I follow a lot of code I found on this site but no results in log. 我遵循在此站点上找到的许多代码,但日志中没有结果。

connection:didReceiveData: can be called multiple times in a connection. connection:didReceiveData:可以在一个连接中被多次调用。 You should have an NSMutableData property that you keep appending data to in connection:didReceiveData: , then work with the data once it is all there in connectionDidFinishLoading . 您应该拥有一个NSMutableData属性,该属性可以将数据追加附加到connection:didReceiveData: ,然后在connectionDidFinishLoading所有存在的数据之后再使用。

I'd suggest adjusting your code to follow those guidelines and seeing if you still have the problem. 我建议您调整代码以遵循这些准则,并查看是否仍然存在问题。


EDIT 编辑
If you are not getting the logs at all, you haven't properly set your class as the NSURLConnectionDelegate . 如果根本没有获取日志,则没有正确将类设置为NSURLConnectionDelegate See the docs for information on what the delegate pattern is and how to make your class the delegate of a framework class in Objective-C. 请参阅文档,以获取有关什么是委托模式以及如何使您的类成为Objective-C中框架类的委托的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM