JSON连接来显示mapView上的标记



我正在尝试执行三个不同的JSON连接来填充一个mapView与标记形成三个不同的MySQL表。

这是我现在要做的代码。为了测试连接,我记录了didReceiveData方法,但是编译器游标没有到达该方法,当然,地图上显示了任何标记。

请您看看我的代码,并告诉我我错过了什么或做错了。谢谢你。

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Geolocalización";

    //carga de datos JSON
    //network activity indicator showed during downloading data
    //PROCESSING FIRST CONNECTION
    first_connection_url = [NSURL URLWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresastodaslist.php"];
    NSURLRequest *first_connection_request = [NSURLRequest requestWithURL:first_connection_url];
    NSURLConnection *first_connection=[[NSURLConnection alloc]initWithRequest:first_connection_request delegate:self];
    //PROCESSING SECOND CONNECTION
    second_connection_url = [NSURL URLWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/centrostodoslist.php"];
    NSURLRequest *second_connection_request = [NSURLRequest requestWithURL:second_connection_url];
    NSURLConnection *second_connection=[[NSURLConnection alloc]initWithRequest:second_connection_request delegate:self];
    //PROCESSING THIRD CONNECTION
    third_connection_url = [NSURL URLWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/eventostodoslist.php"];
    NSURLRequest *thrid_connection_request = [NSURLRequest requestWithURL:third_connection_url];
    NSURLConnection *third_connection=[[NSURLConnection alloc]initWithRequest:second_connection_request delegate:self];

}
//methods to perform the connection and population of data
-(void)connection: (NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if(connection==first_connection){
        data_for_first_connection = [[NSMutableData alloc]init];
    }
    else if(connection==second_connection){
        data_for_second_connection = [[NSMutableData alloc]init];
    }
    else if(connection==third_connection){
        data_for_third_connection = [[NSMutableData alloc]init];
    }
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{
    if(connection==first_connection){
        [data_for_first_connection appendData:thedata];
        NSLog(@"CONEXION 1 AQUI");
    }
    else if(connection==second_connection){
        [data_for_second_connection appendData:thedata];
     NSLog(@"CONEXION 2 AQUI");
    }
    else if(connection==third_connection){
        [data_for_third_connection appendData:thedata];
     NSLog(@"CONEXION 3 AQUI");
    }
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //if data received network indicator not visible
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    if(connection==first_connection) {
        categorias_first = [NSJSONSerialization JSONObjectWithData:data_for_first_connection options:0 error:nil];
    }
    else if(connection==second_connection){
        categorias_second = [NSJSONSerialization JSONObjectWithData:data_for_second_connection options:0 error:nil];
    }
    else if(connection==third_connection){
        // PROCESS TO BE DONE FOR SECOND CONNECTION
        categorias_third = [NSJSONSerialization JSONObjectWithData:data_for_third_connection options:0 error:nil];
    }
    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:27.9847
                                                            longitude:-15.5953
                                                                 zoom:9];
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView_.myLocationEnabled = YES;
     mapView_.delegate = self;
    self.view = mapView_;
    UISegmentedControl *mainSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Ofertas", @"Cursos", @"Eventos", nil]];
    [mainSegment setSegmentedControlStyle:UISegmentedControlStyleBar];
    mainSegment.frame = CGRectMake(20,80, 280, 43);
    //self.navigationItem.titleView = mainSegment;
    //mainSegment.selectedSegmentIndex = nil;
    [mainSegment addTarget:self action:@selector(mainSegmentControl:) forControlEvents: UIControlEventValueChanged];
    [self.view addSubview:mainSegment];

}

更新了测试应用程序的代码。

我已经更新了我的代码来测试它,现在我只使用两个连接。在记录结果时,我检测到数组categoria(在first_connection处)和categoria a2(在second_connection处)是从同一个JSON文件(来自first_connection)填充的:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"Geolocalización";

    //carga de datos JSON
    //network activity indicator showed during downloading data
    [UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    //URL definition where php file is hosted
    //conexion1
    url = [NSURL URLWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresastodaslist.php"];
    request = [NSURLRequest requestWithURL:url];
    first_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];

    //conexion2
    url2 = [NSURL URLWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/centrostodoslist.php"];
    request2 = [NSURLRequest requestWithURL:url];
    second_connection = [[NSURLConnection alloc] initWithRequest:request2 delegate:self];



}
//methods to perform the connection and population of data
-(void)connection: (NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    if ([connection isEqual:first_connection]){
        NSLog(@"FIRST CONNECTION RESPONSE");
        data = [[NSMutableData alloc]init];
    }
    if ([connection isEqual:second_connection]){
        NSLog(@"SECOND CONNECTION RESPONSE");
        data2 = [[NSMutableData alloc]init];
    }

    NSLog(@"ESTOY EN DIDRECEIVERESPONSE");
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)thedata
{

    if ([connection isEqual:first_connection]){
        NSLog(@"FIRST CONNECTION RECEIVED");
       [data appendData:thedata];
    }
    if ([connection isEqual:second_connection]){
        NSLog(@"SECOND CONNECTION RECEIVED");
        [data2 appendData:thedata];
    }


}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //if data received network indicator not visible
    [UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    //array waterfalls populated via JSON from database
    if ([connection isEqual:first_connection]){
    categorias = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSLog(@"DATA1 = %@",categorias);
    }
    if ([connection isEqual:second_connection]){
    categorias2 = [NSJSONSerialization JSONObjectWithData:data2 options:0 error:nil];
        NSLog(@"DATA2 = %@",categorias2);
    }
    NSLog(@"NUMERO DE EMPRESAS OPCION1= %lu"
          , (unsigned long)[categorias count]);
    NSLog(@"NUMERO DE EMPRESAS OPCION2= %lu"
          , (unsigned long)[categorias2 count]);
    // Create a GMSCameraPosition that tells the map to display the
    // coordinate -33.86,151.20 at zoom level 6.
    GMSCameraPosition *camera = [GMSCameraPosition cameraWithLatitude:27.9847
                                                            longitude:-15.5953
                                                                 zoom:9];
    mapView_ = [GMSMapView mapWithFrame:CGRectZero camera:camera];
    mapView_.myLocationEnabled = YES;
     mapView_.delegate = self;
    self.view = mapView_;


    UISegmentedControl *mainSegment = [[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"Ofertas", @"Cursos", @"Eventos", nil]];
    [mainSegment setSegmentedControlStyle:UISegmentedControlStyleBar];
    mainSegment.frame = CGRectMake(20,80, 280, 43);
    //self.navigationItem.titleView = mainSegment;
    //mainSegment.selectedSegmentIndex = nil;
    [mainSegment addTarget:self action:@selector(mainSegmentControl:) forControlEvents: UIControlEventValueChanged];
    [self.view addSubview:mainSegment];

}

我看到了几个问题。首先,你的连接,firstConnection, secondConnection等,是作为局部变量创建的,所以一旦viewDidLoad超出范围,它们就会被释放。当你在委托功能中检查相等性时,它们那时会是nil。您应该为这些连接创建变量或属性。另外,你不应该使用"=="来比较对象,而应该使用isEqual:。

else if([connection isEqual:third_connection]){

正如rdelmar指出的那样,直接的问题是您没有将NSURLConnection引用保存在稍后引用的变量中。这是首先要解决的问题。

更广泛的问题更根本。您启动了三个连接,但是您的connectionDidFinishLoading似乎没有意识到它将被调用三次,每个连接调用一次。值得注意的是,该例程的后一部分,即创建地图视图和段控件,将对三个JSON下载请求中的每个请求执行一次。当然,当所有三个连接都完成时,您只打算做一次与ui相关的事情。

优雅的方法是将这些单独的网络请求包装在NSOperation对象中,并使用操作队列来管理"完成逻辑",其中包括UI的东西。您可以使用AFNetworking实现这一点,或者将NSURLConnection封装在您自己的NSOperation子类中。然后,您可以添加这三个操作,但有一个最终完成操作,取决于其他三个下载操作的完成情况,这将更新UI。

对现有代码的一个更简单的修复是添加三个布尔变量,指示三个单独的下载是否完成。然后,您的connectionDidFinishLoading(每次对三个下载请求调用它)可以为每个请求更新相应的布尔值。然后它只会执行UI相关的东西如果这三个都完成了。

您没有为您的连接调用"start"。

1)为了保持你的代码,你需要为每个连接调用"start",在initWithRequest之后:;
例如,[first_connection start];

2)如果你所需要的(这似乎是情况)是做一个http get和获得NSData响应,你可以简单地做NSData *jsonData = [NSData dataWithContentsOfUrl:[NSURL urlWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresastodaslist.php"]];

3)如果你需要它发生在一个单独的线程中,你可以在一个块中调用dataWithContentsOfUrl,像这样:

<pre>
- (void) getJsonData
{
    //main thread
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
   ^{
       //background thread
       NSData *jsonData = [NSData dataWithContentsOfUrl:[NSURL urlWithString:@"http://mujercanariasigloxxi.appgestion.eu/app_php_files/empresastodaslist.php"]];
       dispatch_async(dispatch_get_main_queue(),
      ^{
          //main thread again
          //parse json and add pins
      });
   });
}
</pre>

祝你好运!

最新更新