我正在尝试通过PHP文件在我的iOS应用程序中返回一个简单的JSON。
.PHP:
<?php
header('Content-Type: application/json');
$myarray = array("io" => 1, "tu" => 2);
$out = json_encode($myarray);
echo $out;
?>
苹果:
-(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");
}
我不明白我做错了什么。我遵循了在这个网站上找到的许多代码,但日志中没有结果。
connection:didReceiveData:
可以在连接中多次调用。您应该有一个 NSMutableData
属性,您可以在 connection:didReceiveData:
中不断追加数据,然后在数据全部包含在connectionDidFinishLoading
中后处理数据。
我建议调整您的代码以遵循这些准则,看看您是否仍然有问题。
编辑
如果根本没有获取日志,则表示您没有将类正确设置为 NSURLConnectionDelegate
。有关委托模式是什么以及如何使您的类成为 Objective-C 中框架类的委托的信息,请参阅文档。