1

我想踏入 mySQL、JSON iPhone 世界。我用我的 Arduino 建立了一个简单的气象站,并将温度发送到我的 MySQL 数据库。我在我的服务器上创建了一个 php 文件。

当我在 Safari 中打开文件时,它看起来像这样:

{"weatherstation":[{"location":"indoor","celsius":"22.85"}]}

现在我想为我的 iPhone 创建一个显示温度的简单应用程序。有人可以帮我写一些代码吗?我在这里搜索堆栈溢出,但大多数人比我更高级。

几乎每个代码都以:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSURL *url = [NSURL URLWithString:@"http://myWebsite.com/myPHPFile.php"];
    NSError *error = nil;

如果有人能帮助我进入这个话题,我将非常感激。

编辑

这是我的 php 文件的一些代码。如何将其更改为 JSON 类型?我试过了

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

但之后我的 php 文件显示了整个 html 结构(<html>...</html>)。如果我将内容类型更改为 json,我是否必须更改 html 部分?

<?php

...

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

...

<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="application/json; charset=utf-8">
  <meta name="viewport" content="user-scalable=yes, width=device-width"> 
  <title>My Temperature</title>
</head>
<body>
 <?php
if(!isset($E)) 
{
?>
{"weatherstation":[{"location":"indoor","celsius":"<?php echo $temp;?>"}]}
<?php           
} 
else 
{
  echo $M;
}
?>   
</body>
</html>
4

2 回答 2

1

使用以下代码,您可以轻松地让您的 json 数据工作

-(void)viewDidLoad{
     //Call function to fetch temperature

     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [self getTemperature];
     });
}


-(void)getTemperature{

    NSData *jsonData=[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://myWebsite.com/myPHPFile.php"]];

    if(jsonData){

        NSJSONSerialization *result=[NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error:nil];

        //Here you get your json parsed        
        NSDictionary *json=(NSDictionary *)result;

        //Get the weather array from your json
        NSArray *arrWeather=[json objectForKey:@"weatherstation"];

        //Loop to get the values

        for(NSDictionary *weather in arrWeather){
             NSLog(@"Temp for Location %@ is %@",[weather objectForKey:@"location"],[weather objectForKey:@"celsius"]);
        }

   }
}

编辑

你的 PHP 应该如下所示你可以直接使用这个版本,因为我已经从代码中删除了前导空格

<?php
    header('Content-Type: application/json');

    if(!isset($E))
    {
?>
{"weatherstation":[{"location":"indoor","celsius":"<?php echo $temp;?>"}]}
<?php
    } 
    else
    {
      echo $M;
    }
?>
于 2013-11-12T20:18:24.353 回答
1

在您的项目中包含AFNetworking,导入"AFHTTPRequestOperationManager.h""AFURLResponseSerialization.h"在您的文件中并使用以下代码:

AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager manager] initWithBaseURL:BASE_URL];
[manager setResponseSerializer:[AFJSONResponseSerializer serializer]];

NSDictionary *parameters = @{@"username" : @"john123", @"type" : @"login"};
[manager POST:@"data.php" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject){
    NSLog(@"response: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
    NSLog(@"error: %@", error);
}];
于 2013-11-12T20:13:36.083 回答