用于在mapView上显示标记的JSON连接

时间:2014-03-12 05:05:58

标签: ios nsurlconnection nsurlrequest nsjsonserialization

我正在尝试执行三个不同的JSON连接,用三个不同的MySQL表格填充带有标记的mapView。

这是我现在要做的代码。为了测试连接,我正在记录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];


}

用于测试APP的更新代码。

我已经更新了我的代码来测试它,现在我只使用两个连接。在记录结果时,我检测到数组的别名(在first_connection)和categoria2(在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];


}

3 个答案:

答案 0 :(得分:3)

我看到了几个问题。例如,您的连接,firstConnection,secondConnection等被创建为局部变量,因此只要viewDidLoad超出范围,它们就会被释放。当您在委托方法中检查相等性时,它们将在那时为零。您应该为这些连接创建ivars或属性。另外,你不应该使用“==”来比较对象,而是使用isEqual:而不是。

else if([connection isEqual:third_connection]){

答案 1 :(得分:1)

正如rdelmar指出的那样,当前的问题是你没有在后面提到的ivars中保存NSURLConnection引用。这是第一件要解决的问题。

更广泛的问题更为根本。您正在启动三个连接,但是您的connectionDidFinishLoading似乎无法识别它将被调用三次,每次连接一次。值得注意的是,该例程的后半部分(即创建地图视图和段控件)将针对三个JSON下载请求中的每一个执行一次。当所有三个连接完成时,你肯定只打算做一次与UI相关的东西。

优雅的方法是将这些单独的网络请求包装在NSOperation个对象中,并使用操作队列来管理包含UI内容的“完成逻辑”。您可以使用AFNetworking实现此功能,或将NSURLConnection包装在您自己的NSOperation子类中。然后你可以添加这三个操作,但是有一个最终的完成操作,这取决于其他三个下载操作的完成,这将更新UI。

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

答案 2 :(得分:0)

你没有为你的联系打电话“开始”。

1)为了保留你的代码,你需要在initWithRequest之后为每个连接调用“start”:
例如,[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>
祝你好运!