2016-08-19 4 views
1

테이블 뷰에로드되지 않는 데이터가 여기에 있습니다. ViewDidLoad 후 NSMutableArray가 비어 있습니다.

  • 내가있는 NSMutableArray에 데이터를 JSON 형태로 나에게 응답 API에서 개체를 추가하려고하지만있는 tableview에로드되지 않습니다.
  • 배열이 정상적으로 설정되어 있지만 tableview를 스크롤하려고 시도 할 때까지 tableview에로드되지 않습니다.

너무 짜증나서 친절하게도 알아낼 수없는 이유를 알 수 없습니다. 백킹 바리 아 :

- (void)viewDidLoad { 

    [SVProgressHUD showWithStatus:@"Please wait ..."]; 


    //get the bookings 
    [self getBookings]; 

    [super viewDidLoad]; 

    [self.tableView reloadData]; 
} 

-(void) getBookings 
{ 
    [email protected]"41"; 
    bookingsList=[[NSMutableArray alloc] init]; 

    NSString *urlAsString = [NSString stringWithFormat:@"http://www.webservice.com/cleaning/api/booking/show/%@/%d",uid,0]; 
    NSURL *url = [[NSURL alloc] initWithString:urlAsString]; 
    NSLog(@"%@", urlAsString); 

    [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc] initWithURL:url] queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

     if (error) { 

      NSLog(@"URL Session Task Failed: %@", [error localizedDescription]); 
     } 
     else { 

      NSArray *postsFromResponse = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil]; 

      NSLog(@"Count %d", postsFromResponse.count); 

      NSLog(@"JSON: %@", postsFromResponse); 

      //remove all objects from array 
      [self.bookingsList removeAllObjects]; 

      for (NSDictionary *attributes in postsFromResponse) { 
       booking *bk = [[booking alloc] init]; 
       [bk setAddress:[attributes objectForKey:@"Address"]]; 
       [bk setBookingId:[attributes objectForKey:@"BookingID"]]; 
       [bk setServiceDate:[attributes objectForKey:@"ServiceDate"]]; 
       [bk setClientName:[attributes objectForKey:@"ClientName"]]; 
       [bk setStatus:[attributes objectForKey:@"Status"]]; 
       [bk setServiceTime:[attributes objectForKey:@"ServiceTime"]]; 
       [bk setPrice:[attributes objectForKey:@"Price"]]; 
       [bk setCleanType:[attributes objectForKey:@"CleanType"]]; 
       [bk setNumOfHours:[attributes objectForKey:@"NumOfHours"]]; 

       //add to array 
       [self.bookingsList addObject:bk]; 

      } 
      NSLog(@"Records found -%lu",(unsigned long)[bookingsList count]); 
      [self.tableView reloadData]; 
      if(bookingsList.count==0) 
      { 
       UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"No Data Alert!" 
                    message:@"No bookings found!" delegate:nil 
                  cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
       //[alertView show]; 
       [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES]; 
      } 

     } 
    }]; 


    [SVProgressHUD dismiss]; 


} 

#pragma mark - TableView Delegate Methods 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    NSLog(@"Total rows - %lu", (unsigned long)[self.bookingsList count]); 
    return [self.bookingsList count]; 
} 
+0

우선 서버에서 성공적으로 응답을 받으셨습니까? – user3182143

+0

예 응답을 받으면 JSON 데이터가 표시됩니다. 내가 말했듯이, 테이블 뷰를 스크롤하려고 할 때 표시됩니다. – Tajuddin

답변

0

사용이 그것은 규칙을 코딩 당신에게

- (void)viewDidLoad { 

    [SVProgressHUD showWithStatus:@"Please wait ..."]; 


    //get the bookings 
    [self getBookings]; 

    [super viewDidLoad]; 
} 

-(void) getBookings 
{ 

    [email protected]"41"; 

    bookingsList=[[NSMutableArray alloc] init]; 

    NSString *urlAsString = [NSString stringWithFormat:@"http://www.webservice.com/cleaning/api/booking/show/%@/%d",uid,0]; 
    NSURL *url = [[NSURL alloc] initWithString:urlAsString]; 
    NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:urlAsString]; 
    [request setHTTPMethod:GET_REQUEST]; 
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"]; 
    NSURLSession *session = [NSURLSession sharedSession]; 
    NSURLSessionDataTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *err) 
            { 

             if (error) { 

              NSLog(@"URL Session Task Failed: %@", [error localizedDescription]); 
             } 
             else { 

              NSArray *postsFromResponse = [NSJSONSerialization JSONObjectWithData: data options:NSJSONReadingMutableContainers error:nil]; 

              NSLog(@"Count %d", postsFromResponse.count); 

              NSLog(@"JSON: %@", postsFromResponse); 

              //remove all objects from array 
              [self.bookingsList removeAllObjects]; 

              for (NSDictionary *attributes in postsFromResponse) { 
               booking *bk = [[booking alloc] init]; 
               [bk setAddress:[attributes objectForKey:@"Address"]]; 
               [bk setBookingId:[attributes objectForKey:@"BookingID"]]; 
               [bk setServiceDate:[attributes objectForKey:@"ServiceDate"]]; 
               [bk setClientName:[attributes objectForKey:@"ClientName"]]; 
               [bk setStatus:[attributes objectForKey:@"Status"]]; 
               [bk setServiceTime:[attributes objectForKey:@"ServiceTime"]]; 
               [bk setPrice:[attributes objectForKey:@"Price"]]; 
               [bk setCleanType:[attributes objectForKey:@"CleanType"]]; 
               [bk setNumOfHours:[attributes objectForKey:@"NumOfHours"]]; 

               //add to array 
               [self.bookingsList addObject:bk]; 

              } 
              NSLog(@"Records found -%lu",(unsigned long)[bookingsList count]); 
              dispatch_async(dispatch_get_main_queue(),^{ 
               [self.tableView reloadData]; 
              }); 
              if(bookingsList.count==0) 
              { 
               UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:@"No Data Alert!" 
                            message:@"No bookings found!" delegate:nil 
                         cancelButtonTitle:@"OK" otherButtonTitles:nil]; 
               //[alertView show]; 
               [alertView performSelectorOnMainThread:@selector(show) withObject:nil waitUntilDone:YES]; 
              } 

             } 
            }]; 
    [task resume]; 


    [SVProgressHUD dismiss]; 


} 


- (void)didReceiveMemoryWarning { 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

#pragma mark - Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

    return 1; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 

    NSLog(@"Total rows - %lu", (unsigned long)[self.bookingsList count]); 
    return [self.bookingsList count]; 
} 
+1

제안 해 주셔서 감사합니다. dispatch_async (dispatch_get_main_queue(),^{ [self.tableView reloadData]; }); 문제가 해결 된 것 같습니다. 나는 [setHTTPMethod : GET_REQUEST] 요청을 대체해야했다. request.HTTPMethod = @ "GET"; – Tajuddin

0

도움이 될 것입니다 - 여기

내 코드입니다 어떤 재산에 대한 표식은 밑줄로 시작해야합니다. _bookingsList처럼. 그 연결을 따르지 않으면 bookingsList에 대한 결과가 저장 될 소스 코드가 없다는 것을 알 수 없습니다.

관련 문제