2014-03-12 5 views
0

3 개의 다른 JSON 연결을 수행하여 mapView에 마커가있는 세 개의 다른 MySQL 테이블을 채우려 고합니다.mapView에 마커를 표시하는 JSON 연결

이것은 지금 제가 수행 한 코드입니다. 연결을 테스트하기 위해 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에서) 제품 분류 및 (second_connection에서) categoria2이 (first_connection에서) 같은 JSON 파일에서 설치되었는지 감지 :

- (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]; 


} 
+0

'initWithRequest'대신 'connectionWithRequest'를 사용할 수 있습니까? – user2071152

+0

@ user2071152 고맙습니다. 지금 시도해 보겠습니다.하지만 문제가 아닌 것 같습니다. 처음에는 연결을 하나만 시도했지만 제대로 작동했습니다. – mvasco

+0

@ user2071152 귀하의 제안은 컴파일러 오류를 발생시킵니다. – mvasco

답변

3

몇 가지 문제점이 있습니다. 하나, 당신의 연결, firstConnection, secondConnection, 등, 지역 변수로 생성됩니다, 그래서 그들은 viewDidLoad 범위를 벗어나 즉시 deallocated됩니다. 델리게이트 메서드에서 동등성을 검사하면 해당 시점에 아무 것도 없을 것입니다. 이러한 연결에 대해 ivars 또는 속성을 만들어야합니다. 또한 객체를 비교하는 데 "=="을 사용하지 말고 대신 isEqual :을 사용하십시오. rdelmar는 지적

else if([connection isEqual:third_connection]){ 
+0

고마워, 나는 ivars를 사용하고 isEqual에 ==를 변경하려고 노력할 것이다 ... – mvasco

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> 

행운을 빕니다!

+1

포인트 1이 잘못되었습니다. initWithRequest : delegate : 메서드를 사용할 때 "start"를 호출 할 필요가 없습니다. 설명서에서 "초기화 된 URL 연결을 반환하고 URL 요청에 대한 데이터로드를 시작합니다"라고 말합니다. – rdelmar

1

당장의 문제는, 당신이 나중에 참조하는 인스턴스 변수에 NSURLConnection 참조를 저장하지 않는 것입니다. 그것이 수정해야 할 첫 번째 문제입니다.

더 광범위한 문제가 더 근본적입니다. 3 개의 연결을 시작했지만 connectionDidFinishLoading은 각 연결에 대해 한 번씩 세 번 호출된다는 사실을 인식하지 못하는 것처럼 보입니다. 특히지도보기와 세그먼트 컨트롤을 만드는 루틴의 후반 부분은 세 가지 JSON 다운로드 요청마다 한 번 수행됩니다. 분명히 세 가지 연결이 완료되었을 때 UI 관련 항목을 한 번만 수행하려고했습니다.

우아한 접근 방식은 NSOperation 개체에 이러한 개별 네트워크 요청을 래핑하고 작업 큐를 사용하여 UI 항목을 포함하는 "완료 논리"를 관리하는 것입니다. AFNetworking으로 구현하거나 하위 클래스에 NSURLConnection을 포함 할 수 있습니다. 그런 다음 세 가지 작업을 추가 할 수 있지만 UI를 업데이트 할 다른 세 가지 다운로드 작업의 완료에 따라 최종 완료 작업이 있습니다.

기존 코드를 더 간단하게 수정하면 세 가지 개별 다운로드가 완료되었는지 여부를 나타내는 3 개의 부울 ivars를 추가 할 수 있습니다. 그런 다음 세 번 다운로드 요청을 할 때마다 호출되는 connectionDidFinishLoading은 각 부울을 각각 업데이트 할 수 있습니다. 그리고 세 가지 모두 완료되면 UI 관련 작업 만 수행합니다.

+0

고맙다. rdelmar가 지적한 것을 구현하기 위해 이미 코드를 변경했다. 테스트하기 위해 두 개의 연결 만 사용하고있다. 이제 connectionDidFinishLoading 메서드를 로깅하고 두 연결을 감지합니다. didReceiveData 메서드에서 각 연결마다 하나의 배열을 채우지 만 두 배열이 첫 번째 연결로 채워지는 것을 해당 메서드에서 로깅했습니다. – mvasco

+0

@mvasco 질문의 마지막 부분에 코드의 최신 번역본을 추가하여 질문을 편집해야합니다. 우리가 코드를 보지 않고 진단하는 것은 불가능할 것입니다. – Rob

+0

고맙습니다. 이제 질문을 편집하여 최신 업데이트를 표시하겠습니다. – mvasco

관련 문제