2013-05-27 2 views
0

내 현재의 문제는 내가 여러 가지 변수 클래스에 SBJSON뿐만 아니라 구문 분석 된 데이터를 사용하여 웹 서비스에서 성공적으로 가져온 데이터가 있습니다. 이제 기본보기 컨트롤러 아이폰 OS에서 액세스 분석 된 JSON 데이터

는 내 기본보기 컨트롤러는 모두 널 (null) 또는

0 나는이 문제를 파악, 웹 서비스하지만 변수에 액세스 할 때마다 데이터를 당기고 클래스 내에서이 변수에 접근하도록되어 응용 프로그램이 주 뷰 컨트롤러에 이미 시작된 경우 웹 서버에서 데이터를 가져 오는 클래스가 아직로드되지 않았기 때문입니다.

어떻게 해결할 수 있습니까?

다음은 기본보기 컨트롤러의 코드입니다.

- (void)viewDidLoad 
{ 

    _mainParser = [[MonroeParser alloc] init]; 
    [_mainParser go]; 

    [super viewDidLoad]; 
    // Do any additional setup after loading the view, typically from a nib. 

    UINavigationBar *navBar = [[self navigationController] navigationBar]; 
    navBar.tintColor = [UIColor redColor]; 
    UIImageView* img = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Power_One_RedLogo.png"]]; 
    self.navigationItem.titleView = img; 

    UIBarButtonItem *iconButton = [[UIBarButtonItem alloc] initWithTitle:@"View Site" style:UIBarButtonItemStylePlain target:self action:@selector(pushToPowerOneWebsite:)]; 
    self.navigationItem.leftBarButtonItem = iconButton; 


    _DayString.text = @"Thursday"; 
    _DayInteger.text = @"24"; 
    _MonthString.text = @"May"; 
    _SystemStatusIcon.image = [UIImage imageNamed:@"Power_One_RedLogo.png"] ; 
    _SystemStatus.text = @"Normal"; 

    [_StatusButton addSubview:_DayInteger]; 



    NSLog(@"%@", _mainParser.solarStatus); 
    NSLog(@"%@", _mainParser.fields); 
    NSLog(@"%@", _mainParser.type); 
    NSLog(@"%@", _mainParser.field); 
    NSLog(@"%@", _mainParser.label); 
    NSLog(@"%ld", (long)_mainParser.entityID); 
    NSLog(@"%@", _mainParser.entityName); 
    NSLog(@"%@", _mainParser.timeZone); 
    NSLog(@"%@", _mainParser.units); 
    NSLog(@"%@", _mainParser.parameters); 
    NSLog(@"%ld", (long)_mainParser.param_Value); 
    NSLog(@"%@", _mainParser.param_Name); 
    NSLog(@"%ld", (long)_mainParser.start); 
    NSLog(@"%@", _mainParser.startLabel); 
    NSLog(@"%ld", (long)_mainParser.end); 
    NSLog(@"%@", _mainParser.endLabel); 
    NSLog(@"%ld", (long)_mainParser.value); 
} 

내 클래스 파서 번호 :

- (void) go 
{ 
    adapter = [[SBJsonStreamParserAdapter alloc] init]; 
    adapter.delegate = self; 

    parser = [[SBJsonStreamParser alloc] init]; 
    parser.delegate = adapter; 

    parser.supportMultipleDocuments = YES; 

    NSString *url = myurl; 

    NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 

    theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 
} 

#pragma mark SBJsonStreamParserAdapterDelegate methods 

- (void)parser:(SBJsonStreamParser *)parser foundArray:(NSArray *)array 
{ 
    [NSException raise:@"unexpevted" format:@"Should not get here"]; 
} 


- (void)parser:(SBJsonStreamParser *)parser foundObject:(NSDictionary *)dict 
{ 
    solarStatus = [dict objectForKey:@"status"]; 
    fields = [dict objectForKey:@"fields"]; 
    type = [[dict objectForKey:@"fields"] valueForKey:@"type"]; 
    field = [[dict objectForKey:@"fields"] valueForKey:@"field"]; 
    label = [[dict objectForKey:@"fields"] valueForKey:@"label"]; 
    entityID = [[dict objectForKey:@"fields"] valueForKey:@"entityID"]; 
    entityName = [[dict objectForKey:@"fields"] valueForKey:@"entityName"]; 
    timeZone = [[dict objectForKey:@"fields"] valueForKey:@"entityName"]; 
    units = [[dict objectForKey:@"fields"] valueForKey:@"units"]; 
    parameters = [[dict objectForKey:@"fields"] valueForKey:@"parameters"]; 
    param_Value = [[[dict objectForKey:@"fields"] valueForKey:@"parameters"]valueForKeyPath:@"value"]; 
    param_Name = [[[dict objectForKey:@"fields"] valueForKey:@"parameters"]valueForKeyPath:@"name"]; 
    start = [[dict objectForKey:@"fields"] valueForKey:@"start"]; 
    startLabel = [[dict objectForKey:@"fields"] valueForKey:@"startLabel"]; 
    end = [[dict objectForKey:@"fields"] valueForKey:@"end"]; 
    endLabel = [[dict objectForKey:@"fields"] valueForKey:@"endLabel"]; 
    value = [[dict objectForKey:@"fields"] valueForKey:@"value"]; 



    NSLog(@"%@", solarStatus); 
    NSLog(@"%@", fields); 
    NSLog(@"%@", type); 
    NSLog(@"%@", field); 
    NSLog(@"%@", label); 
    NSLog(@"%ld", (long)entityID); 
    NSLog(@"%@", entityName); 
    NSLog(@"%@", timeZone); 
    NSLog(@"%@", units); 
    NSLog(@"%@", parameters); 
    NSLog(@"%ld", (long)param_Value); 
    NSLog(@"%@", param_Name); 
    NSLog(@"%ld", (long)start); 
    NSLog(@"%@", startLabel); 
    NSLog(@"%ld", (long)end); 
    NSLog(@"%@", endLabel); 
    NSLog(@"%ld", (long)value); 

} 
#pragma mark NSURLConnectionDelegate methods 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    NSLog(@"Connection didReceiveResponse: %@ - %@", response, [response MIMEType]); 
} 



- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 
{ 
    NSLog(@"Connection didReceiveAuthenticationChallenge: %@", challenge); 

    NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceForSession]; 

    [[challenge sender] useCredential:credential forAuthenticationChallenge:challenge]; 
} 



- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    NSLog(@"Connection didReceiveData of length: %u", data.length); 

    SBJsonStreamParserStatus status = [parser parse:data]; 

    if (status == SBJsonStreamParserError) 
    { 
     solarStatus = [NSString stringWithFormat:@"The parser encountered an error: %@", parser.error]; 
     NSLog(@"Parser error: %@", parser.error); 

    } else if (status == SBJsonStreamParserWaitingForData) { 
     NSLog(@"Parser waiting for more data"); 
    } 
} 



- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]); 
} 



- (void)connectionDidFinishLoading:(NSURLConnection*)connection 
{ 
    NSLog(@"Connection finished"); 
} 

클래스 분석기의 출력은 실제 데이터와 함께 올바른 문자열을 출력한다. 하지만 문제는 메인보기 컨트롤러에서 동일한 DATA를 출력 할 때 모든 것이 NULL 또는 0을 반환합니다.

내가 말했듯이, 클래스 파서가 검색하기 전에 메인보기 컨트롤러로드 문제가 있다고 확신합니다. JSON 개체의 데이터를 가져옵니다.

도움이 될 것입니다 !!!

또한 제가 조사를 좀 해봤 내가 웹 서비스 나 데이터를 가져 오는하고 있지만 이러한 구현에 매우 새로운 오전에 비동기 호출을 사용하는 함수를 구현해야 할 것 같다.

당신은이 일을해서는 안

2013-05-27 16:18:26.580 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.585 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.585 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.586 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.586 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.586 PowerOneAuroraApp[14230:c07] 0 
2013-05-27 16:18:26.586 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.587 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.587 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.587 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.588 PowerOneAuroraApp[14230:c07] 0 
2013-05-27 16:18:26.588 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.588 PowerOneAuroraApp[14230:c07] 0 
2013-05-27 16:18:26.603 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.603 PowerOneAuroraApp[14230:c07] 0 
2013-05-27 16:18:26.603 PowerOneAuroraApp[14230:c07] (null) 
2013-05-27 16:18:26.604 PowerOneAuroraApp[14230:c07] 0 
2013-05-27 16:18:27.092 PowerOneAuroraApp[14230:c07] Connection didReceiveResponse: <NSHTTPURLResponse: 0x7539100> - application/json 
2013-05-27 16:18:27.092 PowerOneAuroraApp[14230:c07] Connection didReceiveData of length: 2154 
2013-05-27 16:18:27.094 PowerOneAuroraApp[14230:c07] SUCCESS 
2013-05-27 16:18:27.095 PowerOneAuroraApp[14230:c07] (
     { 
     end = 1369696440000; 
     endLabel = "Mon May 27, 2013 5:14:00 PM MDT"; 
     entityId = 1167815; 
     entityName = "Morone Residence"; 
     field = GenerationPower; 
     label = now; 
     parameters =   (
     ); 
     start = 1369696440000; 
     startLabel = "Mon May 27, 2013 5:14:00 PM MDT"; 
     timeZone = "US/Mountain"; 
     type = instant; 
     units = kilowatts; 
     value = "0.229000000283"; 
    }, 
     { 
     end = 1369696707064; 
     endLabel = 20130527171827; 
     entityId = 1167815; 
     entityName = "Morone Residence"; 
     field = GenerationEnergy; 
     label = today; 
     parameters =   (
         { 
       name = "DataItem.now.maxCacheAge"; 
       value = 60; 
      } 
     ); 
     sampleEnd = 1369692840000; 
     sampleEndLabel = 20130527161400; 
     sampleStart = 1369634340000; 
     sampleStartLabel = 20130526235900; 
     start = 1369634400000; 
     startLabel = 20130527000000; 
     timeZone = "US/Mountain"; 
     type = window; 
     units = "kilowatt-hours"; 
     value = "7.95501708984"; 
    }, 
     { 
     end = 1369696707064; 
     endLabel = 20130527171827; 
     entityId = 1167815; 
     entityName = "Morone Residence"; 
     field = GenerationEnergy; 
     label = week; 
     parameters =   (
         { 
       name = "DataItem.now.maxCacheAge"; 
       value = 60; 
      } 
     ); 
     sampleEnd = 1369692840000; 
     sampleEndLabel = 20130527161400; 
     sampleStart = 1369547940000; 
     sampleStartLabel = 20130525235900; 
     start = 1369548000000; 
     startLabel = 20130526000000; 
     timeZone = "US/Mountain"; 
     type = window; 
     units = "kilowatt-hours"; 
     value = "16.60800170898"; 
    }, 
     { 
     end = 1369696707064; 
     endLabel = 20130527171827; 
     entityId = 1167815; 
     entityName = "Morone Residence"; 
     field = GenerationEnergy; 
     label = month; 
     parameters =   (
         { 
       name = "DataItem.now.maxCacheAge"; 
       value = 60; 
      } 
     ); 
     sampleEnd = 1369692840000; 
     sampleEndLabel = 20130527161400; 
     sampleStart = 1367387940000; 
     sampleStartLabel = 20130430235900; 
     start = 1367388000000; 
     startLabel = 20130501000000; 
     timeZone = "US/Mountain"; 
     type = window; 
     units = "kilowatt-hours"; 
     value = "269.87199401855"; 
    }, 
     { 
     end = 1369692840000; 
     endLabel = "Mon May 27, 2013 4:14:00 PM MDT"; 
     entityId = 1167815; 
     entityName = "Morone Residence"; 
     field = GenerationEnergy; 
     label = lifetime; 
     parameters =   (
     ); 
     start = 1369692840000; 
     startLabel = "Mon May 27, 2013 4:14:00 PM MDT"; 
     timeZone = "US/Mountain"; 
     type = instant; 
     units = "kilowatt-hours"; 
     value = "1609.48400878906"; 
    } 
) 
2013-05-27 16:18:27.097 PowerOneAuroraApp[14230:c07] (
    instant, 
    window, 
    window, 
    window, 
    instant 
) 
2013-05-27 16:18:27.098 PowerOneAuroraApp[14230:c07] (
    GenerationPower, 
    GenerationEnergy, 
    GenerationEnergy, 
    GenerationEnergy, 
    GenerationEnergy 
) 
2013-05-27 16:18:27.098 PowerOneAuroraApp[14230:c07] (
    now, 
    today, 
    week, 
    month, 
    lifetime 
) 
2013-05-27 16:18:27.098 PowerOneAuroraApp[14230:c07] 124196320 
2013-05-27 16:18:27.099 PowerOneAuroraApp[14230:c07] (
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence" 
) 
2013-05-27 16:18:27.099 PowerOneAuroraApp[14230:c07] (
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence", 
    "Morone Residence" 
) 
2013-05-27 16:18:27.099 PowerOneAuroraApp[14230:c07] (
    kilowatts, 
    "kilowatt-hours", 
    "kilowatt-hours", 
    "kilowatt-hours", 
    "kilowatt-hours" 
) 
2013-05-27 16:18:27.104 PowerOneAuroraApp[14230:c07] (
     (
    ), 
     (
       { 
      name = "DataItem.now.maxCacheAge"; 
      value = 60; 
     } 
    ), 
     (
       { 
      name = "DataItem.now.maxCacheAge"; 
      value = 60; 
     } 
    ), 
     (
       { 
      name = "DataItem.now.maxCacheAge"; 
      value = 60; 
     } 
    ), 
     (
    ) 
) 
2013-05-27 16:18:27.105 PowerOneAuroraApp[14230:c07] 124196576 
2013-05-27 16:18:27.105 PowerOneAuroraApp[14230:c07] (
     (
    ), 
     (
     "DataItem.now.maxCacheAge" 
    ), 
     (
     "DataItem.now.maxCacheAge" 
    ), 
     (
     "DataItem.now.maxCacheAge" 
    ), 
     (
    ) 
) 
2013-05-27 16:18:27.106 PowerOneAuroraApp[14230:c07] 124196720 
2013-05-27 16:18:27.106 PowerOneAuroraApp[14230:c07] (
    "Mon May 27, 2013 5:14:00 PM MDT", 
    20130527000000, 
    20130526000000, 
    20130501000000, 
    "Mon May 27, 2013 4:14:00 PM MDT" 
) 
2013-05-27 16:18:27.106 PowerOneAuroraApp[14230:c07] 124196784 
2013-05-27 16:18:27.106 PowerOneAuroraApp[14230:c07] (
    "Mon May 27, 2013 5:14:00 PM MDT", 
    20130527171827, 
    20130527171827, 
    20130527171827, 
    "Mon May 27, 2013 4:14:00 PM MDT" 
) 
2013-05-27 16:18:27.107 PowerOneAuroraApp[14230:c07] 124196848 
2013-05-27 16:18:27.107 PowerOneAuroraApp[14230:c07] Parser waiting for more data 
2013-05-27 16:18:27.107 PowerOneAuroraApp[14230:c07] Connection finished 

답변

1

OUTPUT. URL을 동기화하기 전까지는 URL을 통해 정보를 가져올 수 없기 때문에 UI가 완료 될 때까지 viewdidload에 갇히게됩니다.

내가 SBJSON에 익숙하지 않아요하지만 대부분의 아마 대리자 메서드 호출 또는 completition 처리기 블록 중 하나가 있습니다, 당신은 거기 검색된 정보를 처리해야합니다.

편집 : 실은 저의 잘못으로 json 데이터를 얻기 위해 NSURLConnection을 사용하고 있다는 사실을 몰랐습니다. 게다가 코드에서 다른 이상한 것들을 볼 수 있습니다.

사과 설명서 here을 확인하고 메인 컨트롤러에 connectionDidFinishLoading을 구현하기 만하면됩니다.

당신은 JSON 데이터의 응답을 한 후에 당신은 당신의 파서를 제공해야하고 당신이 정보를 사용할 수 있습니다.

이 코드에서 내가 연결 대리자를 볼 수 없습니다도 어디서든 당신은 당신의 파서에이 데이터를 공급하고 있습니다. this처럼

:

SBJsonParser *jsonParser = [[SBJsonParser alloc] init]; 
NSError *error = nil; 
NSArray *jsonObjects = [jsonParser objectWithString:jsonString error:&error]; 
[jsonParser release], jsonParser = nil; 

그러나 그것은 내가 제대로 그 일을한다고 가정 때문에 나타납니다 로그에

.

확인 로그,

연결 didReceiveResponse :이 호출이 나타나기 전에 사용자가 데이터를 요청 후에

가 나타납니다, 그래서 아무것도 프로그래머 없습니다. 해당 메소드에 대한 정보를 구문 분석하는 데 사용하는 코드를 이동하십시오.

+0

이것은 WAS 내가해야 할 일을했을하지만 JSON 객체에 아주 새로운 오전 콜백 및 완료 핸들러 블록의 이러한 종류의 처리 낸 것. 누구든지이 작업을 수행하는 방법에 대한 예제가있는 경우 .... 크게 감사하겠습니다 !!! 나는 SBJSON API 문서를 참고했지만, 내가 말했듯이, 나는 아주 새롭고, 나를 궤도에 올려 놓는 예가 매우 도움이 될 것이다. 다행히도 다른 사람이 같은 문제를 가지고 해결 했으므로이 문제를 해결하는 데 며칠이 걸리지 않으면 시간이 걸리지 않을 것입니다. – jsetting32

+0

체크 편집, 이것이 당신이 일을하고있다,하지만 난 수정은 매우 간단하다 생각하는 방법을 잘 전체 코드 메신저하지 아니기 때문에. (코드를 그만큼 dofinishloading 대리자 호출로 옮깁니다) – Pochi