2014-04-10 3 views
0

내 응용 프로그램에 약간의 문제가 있습니다. 일부 http 요청을 서버에 비동기 적으로 보내려고합니다. 나는이 방법 작성 :비동기 http 게시 방법 - ios

- (void)sendHTTPRequest:(NSString *)urlString type:(NSString *)type idNegozio:(NSNumber *)idNegozio { 

    self.negozi = [[NSMutableArray alloc] init]; 
    NSData *jsonData; 
    NSString *jsonString; 

    if ([type isEqualToString:@"shops"]) { 

     self.reqNeg = YES; 
     self.reqApp = NO; 

...

jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil]; 
    jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; 



    else if ([type isEqualToString:@"appointments"]) 
    { 
     [self.loadingIconApp startAnimating]; 

     self.reqNeg = NO; 
     self.reqApp = YES; 

...

  jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary options:0 error:nil]; 
      jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding]; 

    NSString *requestString = [NSString stringWithFormat:urlString]; 
     NSURL *url = [NSURL URLWithString:requestString]; 
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30]; 
    [urlRequest setHTTPMethod:@"POST"]; 
    [urlRequest setHTTPBody: jsonData]; 

    NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:urlRequest delegate:self]; 

    [conn start]; 

}

을 내가 연결을 위해이 방법을 사용하십시오

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { 
    self.responseData = [[NSMutableData alloc] init]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
    [self.responseData appendData:data]; 
} 

- (NSCachedURLResponse *)connection:(NSURLConnection *)connection 
        willCacheResponse:(NSCachedURLResponse*)cachedResponse { 
    return nil; 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection { 

    if (self.reqNeg == YES) { 
     //here use the responseData for my first http request 
    } 

    if (self.reqApp == YES) { 

     //here use the responseData for second http request 
    } 


} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { 

} 

하지만이 방법으로는 첫 번째 연결 만 작동하며 responseData를 사용할 수 있습니다. 반면, 다른 http 요청을 보내려고하면 connectionDidFinishLoading 메서드가 작동하지 않고 다른 메서드도 작동하지 않습니다. 누구나 아이디어가 있습니까 ??

+0

귀하의 CONN 객체는 지역 변수, 당신은해야한다 그것은 클래스의 멤버 변수입니다. 동시에 물건을 보내려고하십니까? 동시에 전송되는 각각의 항목에 대해 별도의 NSURLConnection을 사용하거나, 하나씩 사용하지만 하나씩 만 보내십시오. 첫 번째 보내기가 완료되기 전에 sendHTTPRequest를 두 번 이상 호출하면 코드를 사용하여 – Gruntcakes

+0

각 요청을 한 번에 하나씩 만 보낼 때마다 이전 NSURLConnection 개체를 새 것으로 덮어 씁니다. 그리고 첫 번째 요청이 성공으로 끝났을 것입니다. 하지만 두 번째 요청이 시작되지 않는 것 같습니다 – Alex

답변

0

코드가 잘 보입니다. 여기 내 아이디어는 다음과 같습니다.

두 번째 NSURLConnection을 만들고 보내고 있습니까? 아마도 전송되지 않을 수도 있습니다.

두 번째 연결이 계속 전송되는 동안 sendHTTPRequest : type : idNegozio : 메서드를 다른 유형으로 호출하고 있습니까?
보내기 기능을 시작할 때 아직 연결을 보내지 않았는지 확인하지 않아도됩니다. 어쩌면 당신의 깃발이 중간 연결로 바뀔지도 모릅니다.

didFinish 메서드의 if 문은 else와 결합되어야합니다. 만약 당신이 실수로 넘어지지 않고 응답을 두 번 처리하려고 시도하는 'neg'연결을 처리 한 후에 'app'연결을 끊기를 원한다면.

또한 생성자의 startImmediately : 매개 변수에 NO를 전달하지 않으면 NSURLConnection에서 'start'를 명시 적으로 호출 할 필요가 없습니다. 그래도 문제가 발생해서는 안됩니다. 당신이 하나를 사용하여 비동기 요청을 사용하려면

+0

도와 주셔서 감사합니다.이 오류가 있기 때문에 연결이 시작되지 않는다는 것을 이해합니다. 도메인 = NSURLErrorDomain 코드 = -1002 "지원되지 않는 URL" – Alex

2

해당 작업을 수행 할 수 있습니다

- (void)request1 { 
    NSString *requestString = @"your url here"; 
    NSOperationQueue *queue = [[NSOperationQueue alloc] init]; 
    [NSURLConnection sendAsynchronousRequest:[[NSURLRequest alloc]initWithURL:[NSURL URLWithString: requestString]] 
            queue:queue 
         completionHandler: 
    ^(NSURLResponse *response, NSData *data, NSError *error) { 
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    if (!error && httpResponse.statusCode >= 200 && httpResponse.statusCode <300) { 
     // call the request2 here which is similar to request 1 
     // your request2 method here 
    } 
    }]; 
} 

희망이 도움이 ~ ~ 감사합니다

+0

도움에 감사드립니다. – Alex