2014-03-19 1 views
0

서버에서 데이터를 가져 오는 다음 코드가 있습니다.NSHTTPURLResponse 해제 메시지가 할당 취소 된 인스턴스로 전송되었습니다.

-(void)loginForFaceBook 
    { 


     GTMOAuth2ViewControllerTouch *viewController; 
     viewController = [[GTMOAuth2ViewControllerTouch alloc] 
      initWithScope:@"https://www.googleapis.com/auth/plus.me" 
      clientID:@"27615...6qdi60qjmachs.apps.googleusercontent.com" 

      clientSecret:@"Fs8A...u2PH" 

                keychainItemName:@"OAuth2 Sample:  
      Google+" 
                  delegate:self 

     finishedSelector:@selector(viewController:finishedWithAuth:error:)]; 

     [[self navigationController] pushViewController:viewController 
              animated:YES]; 


     } 


    - (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController 
     finishedWithAuth:(GTMOAuth2Authentication *)auth 
        error:(NSError *)error { 



    if (error != nil) { 
     // Authentication failed (perhaps the user denied access, or closed the 
     // window before granting access) 
     NSLog(@"Authentication error: %@", error); 
     NSData *responseData = [[error userInfo] objectForKey:@"data"]; // 
     kGTMHTTPFetcherStatusDataKey 
      if ([responseData length] > 0) { 
      // show the body of the server's authentication failure response 
//     NSString *str = [[NSString alloc] initWithData:responseData 
//             encoding:NSUTF8StringEncoding]; 
    //   NSLog(@"%@", str); 
    } 

//  self.auth = nil; 
     } else { 
//   NSString *authCode = [NSString alloc]in; 
     NSMutableURLRequest * request; 
     request = [[NSMutableURLRequest alloc] initWithURL:[NSURL  
     URLWithString:@"http://api.kliqmobile.com/v1/tokens"] 

     cachePolicy:NSURLRequestReloadIgnoringCacheData 
             timeoutInterval:60] ; 
      NSLog(@"%@",auth); 
      NSLog(@"ho gya success %@ :::: %@ :::: %@", auth.accessToken, 
      auth.refreshToken, auth.code); 
      NSMutableURLRequest * response; 
     NSError    * error; 

      request.URL = [NSURL URLWithString:@"http://api.kliqmobile.com/v1/tokens"]; 
      NSString *post = [NSString stringWithFormat:@" 
      {\"token\":\"%@\",\"secret\":\"%@\",\"service\":\"%@\",\"handle\":\"%@\"}", 
      auth.accessToken,auth.code,@"google",nil]; 
      NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding 
      allowLossyConversion:YES]; 
      NSString *postLength = [NSString stringWithFormat:@"%d",[postData length]]; 
      [request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
      [request setValue:@"application/x-www-form-urlencoded" 
      forHTTPHeaderField:@"Content-Type"]; 
     [request setHTTPMethod:@"POST"]; 
     [request setHTTPBody:postData]; 
     error  = nil; 
     response = nil; 

      NSURLConnection *connection = [NSURLConnection connectionWithRequest:request 
     delegate:self]; 
     [connection start]; 

    } 

나는 NSURLConnection delegtes 방법을 구현하고 데이터는이

- (void)connection:(NSURLConnection*)connection didReceiveData:(NSData*)data 
{ 
    NSMutableURLRequest * response; 
    NSError    * error; 
    NSLog(@"Did Receive Data %@", [[NSString alloc]initWithData:data 
                 encoding:NSUTF8StringEncoding]); 
    NSMutableURLRequest * requestContacts; 
    requestContacts = [[NSMutableURLRequest alloc] initWithURL:[NSURL 
                   URLWithString:@"http://api.kliqmobile.com/v1/contacts"] 

                cachePolicy:NSURLRequestReloadIgnoringCacheData 
               timeoutInterval:60] ; 
    [requestContacts setHTTPMethod:@"GET"]; 
    [requestContacts setAllHTTPHeaderFields:headers]; 
    error  = nil; 
    response = nil; 

    NSData* data1 = [NSURLConnection sendSynchronousRequest:requestContacts 
              returningResponse:&response error:&error]; 

    NSLog(@"WE GET THE REQUIRED TOKAN DATA %@ :: %@ :: %@", [[NSString alloc] 
                  initWithData:data1 encoding: NSASCIIStringEncoding], error ,response); 



} 

처럼 잘 인쇄되어 있지만 내 애플 추락 얻을 후에는 다음과 같은 오류를주고있다;

[NSHTTPURLResponse release] : 해제 된 인스턴스 0xcb51070에 메시지가 전송되었습니다.

제발 어떻게하는지 알려주세요.

답변

0

생각을 몇 :

  1. 당신의 didReceiveData 방법의 목적은 무엇입니까? 당신은 정말 NSURLConnectionDataDelegate 방법의 중간에 동기 네트워크 요청을 수행해서는 안

    • : 여기에 문제의 무리가 있습니다.

    • 동기 요청을 전혀 수행하지 말고 비동기 적으로 수행해야합니다.

    • 데이터 수신과이 새로운 요청 생성 간의 연결은 무엇입니까? 요청에있는 데이터를 사용하고 있지 않으므로 여기에서 왜해야합니까?

    전형적인 패턴은 : didReceiveResponse 일부 클래스 속성에 NSMutableData 개체를 인스턴스화해야

    • .

    • didReceiveData의 유일한 기능은 수신 된 데이터를 NSMutableData에 추가하는 것입니다. 이 메소드는 모든 데이터가 수신되기 전에 여러 번 호출 될 수 있습니다.

    • connectionDidFinishLoading에서 요청을 완료하면 수행 할 다음 단계를 시작해야합니다. 초기 요청이 완료되면 다른 비동기 네트워크 요청을 시작하려면 여기에서 수행하십시오.

    • didFailWithError에서 분명히 연결 실패를 처리합니다. 당신이 connectionWithRequest를 호출 할 때

  2. , 당신은 start 방법을 사용해서는 안됩니다. initWithRequest:delegate:startImmediately:startImmediately 매개 변수로 사용하는 경우 NO을 사용할 때만 start을 사용하십시오. 그렇지 않으면 자동으로 연결이 시작되고 두 번째 만 시작됩니다.

  3. 원래 질문과 관련이 없지만 post 문자열을 만들면 올바르지 않을 수 있습니다. 매개 변수 값이 누락되었습니다.JSON을 수동으로 생성하는 대신 NSDictionary을 사용하고 NSJSONSerialization을 사용하여이 사전의 JSON을 포함하는 NSData 개체를 만듭니다. 그게 훨씬 더 안전 : 분명히

    NSDictionary *params = @{@"token" : auth.accessToken, 
             @"secret" : auth.code, 
             @"service" : @"google", 
             @"handle" : @""}; 
    NSError *error; 
    NSData *postData = [NSJSONSerialization dataWithJSONObject:params options:0 error:&error]; 
    

    , 당신은 handle 값에 필요한 어떤 공급.

  4. 접선 프로세스 관련 관찰이지만 Xcode가 제공하는 모든 기능을 활용하고 있는지 궁금합니다. 예를 들어 responseNSMutableURLRequest으로 선언 한 다음이 매개 변수를 sendSynchronousRequest에 사용하면 컴파일러 경고가 생성됩니다. 내 stringWithFormatpost 문자열 (내 세 번째 포인트)에 대해서도 마찬가지입니다. 그것은 경고를 발생시켜야합니다.

    이 두 가지는 즉시 관련이 없지만 다른 컴파일 타임 경고에주의하지 않는지 궁금합니다. 이러한 경고는 강력한 코드를 작성할 때 가장 친한 친구이며 모두 해결할 것을 권장합니다. 한 단계 더 이동하려면, 당신은 또한 ("제품"메뉴 또는 변화 + 명령 + B에 "분석") 정적 분석을 통해 프로젝트를 실행해야하고, 너무, 그것은 지적 아무것도 해결.