2013-08-12 2 views
-2

sendSynchronousRequest를 사용하여 NSURLConnection에 대한 내 코드가 올바르게 작동하지만 어떻게 비동기 요청으로 변경할 수 있습니까? 나는 많이 시도했지만 아무 일도 없을 것이다.NSURLConnection을 sendSynchronousRequest에서 sendAsynchronousRequest로 변경 하시겠습니까?

요청이 비어 있으면 [[]]이 (가) 빈 배열을 가져옵니다. 경고 메시지를 잡으려면 어떻게해야합니까? 당신은 할 수

도와주세요 ...

 [UIApplication sharedApplication].networkActivityIndicatorVisible = YES; 

    NSString *urlString = @"http://www.xyz.at/sample.php"; 

    NSURL *url = [NSURL URLWithString:urlString]; 

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
    [request setURL:url]; 
    [request setHTTPMethod:@"POST"]; 

    NSMutableData *body = [NSMutableData data]; 

    NSString *postWerte = [NSString stringWithFormat:@"id=%@", self.textfeld.text]; 

    [body appendData:[postWerte dataUsingEncoding:NSUTF8StringEncoding]]; 

    [request setHTTPBody:body]; 

    NSError *error = nil; 
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error]; 
    NSLog(@"Error: %@", error.description); 

    NSString *returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding]; 

    const char *convert = [returnString UTF8String]; 
    NSString *responseString = [NSString stringWithUTF8String:convert]; 
    NSMutableArray *meinErgebnis = [responseString JSONValue]; 

    NSString *cycle = @""; 

    NSString *kopfdaten = [NSString stringWithFormat:@"Sendungsart: %@\r\nGewicht: %@ kg\r\n\r\n", [[meinErgebnis objectAtIndex:0] objectForKey:@"ParcelTypeDescription"], [[meinErgebnis objectAtIndex:0] objectForKey:@"Weight"]]; 

    cycle = [cycle stringByAppendingString:kopfdaten]; 

    for(int i = 1; i < meinErgebnis.count; i++) 
     { 

     NSString *myValue = [NSString stringWithFormat:@"%@  PLZ: %@\r\nStatus: %@\r\n\r\n", 
       [[meinErgebnis objectAtIndex:i] objectForKey:@"EventTimestamp"], 
       [[meinErgebnis objectAtIndex:i] objectForKey:@"EventPostalCode"], 
       [[meinErgebnis objectAtIndex:i] objectForKey:@"ParcelEventReasonDescription"]]; 

     cycle = [cycle stringByAppendingString:myValue]; 

     } 
     self.ergebnis.text = [NSString stringWithFormat:@"%@", cycle]; 

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO; 
    [self.textfeld resignFirstResponder]; 
+0

비동기 요청을 시도한 코드를 표시해야합니다. 그러면 누군가가 문제를 해결하도록 도와 줄 수 있습니다. –

+0

'for' 루프에서 인덱스가 0 인 첫 번째 항목을 건너 뛰었습니까? – Rob

답변

3

: 완료 블록 내부에 NSData 처리의 모든 코드를 배치

  • NSOperationQueue를 만들고,

  • 전화 sendAsynchronousRequest, .

    NSURLResponse *response = nil; 
    NSError *error = nil; 
    NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
    
    // now process resulting `data` 
    

    사용 : 대신 따라서

,

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

    // now process resulting `data` 
}]; 

또는, NSURLConnectionDataDelegate 방법을 구현할 수 있습니다. 이에 대한 자세한 내용은 URL 로딩 시스템 프로그래밍 가이드의 Using NSURLConnection 섹션을 참조하십시오. "요청이 비어있는 경우"


당신은 말한다 : 나는 "반환 된 데이터가 비어있는 경우"무슨 뜻 가정합니다. 그리고 당신은 그것이 [[]]라고 말합니다. 그게 실제로 얻는 것이라면, 하나의 항목을 가진 배열처럼 들립니다 (그 자체는 빈 배열입니다). 아니면 [] (빈 배열입니까?)입니까? 아니면 nil입니까?

반환 할 데이터가 []이고 빈 배열이라고 가정합니다.

NSJSONSerialization, 내장 된 JSON 파서를 사용하는 것이 좋습니다. 실제로 원할 경우 분명히 JSONValue을 사용할 수 있습니다.

마지막으로 구현에서 첫 번째 항목 (NSArray은 0부터 시작하는 인덱스 사용)을 건너 뜁니다. 나는 그것이 의도하지 않았다고 가정하고있다.

NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) { 

    if (error) { 
     NSLog(@"%s: sendAsynchronousRequest error: %@", __FUNCTION__, error); 
     return; 
    } 

    NSError *parseError; 
    NSArray *meinErgebnis = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError]; 

    if (parseError) { 
     NSLog(@"%s: JSONObjectWithData error: %@", __FUNCTION__, parseError); 
     return; 
    } 

    if ([meinErgebnis count] == 0) { 
     NSLog(@"%s: meinErgebnis empty", __FUNCTION__); 
     return; 
    } 

    for (NSDictionary *dictionary in meinErgebnis) 
    { 
     // now process each dictionary entry in meinErgebnis 
    } 

    // etc. 
}];