2015-06-18 91 views
1

我必須做SSL固定,因此需要驗證服務器端SSL證書。 所以我必須使用NSURL代表。我在我所創建方法的輔助類返回我登錄響應:NSUrlConnection委託方法沒有從幫助類中調用

- (NSData *)sendSynchronousRequest:(NSString *)strNewLoginRequest 
      returningResponse:(NSURLResponse **)response 
         error:(NSError **)error { 
NSMutableURLRequest *finalRequest = nil; 

NSURL *url= [NSURL URLWithString:const_url]; 

finalRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30.0]; 

NSData *requestData = [NSData dataWithBytes:[strLoginRequest UTF8String] length:[strLoginRequest length]]; 

    self.connection = [[NSURLConnection alloc] initWithRequest:finalRequest delegate:self startImmediately:NO]; 

    NSRunLoop *currentRunLoop = [NSRunLoop currentRunLoop]; 
    [self.connection unscheduleFromRunLoop:currentRunLoop forMode:NSDefaultRunLoopMode]; 
    [self.connection scheduleInRunLoop:currentRunLoop forMode:@"connectionRunLoopMode"]; 

    [self.connection start]; 

    while ([currentRunLoop runMode:@"connectionRunLoopMode" beforeDate:[NSDate distantFuture]]); 

    return self.mutableResponse; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    self.response = response; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    self.mutableResponse = [[NSMutableData alloc]init]; 
    [self.mutableResponse appendData:data]; 

} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    dispatch_async(dispatch_get_main_queue(), ^{ 

    if (loadingView) 
    { 
     [loadingView removeView]; 
    } 

    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Failure" message:@"Network Failure" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil]; 

     [alert show]; 
    }); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    if (loadingView) 
    { 
     [loadingView removeView]; 
    } 
    self.resultString = [[NSString alloc] initWithData:self.mutableResponse  encoding:NSASCIIStringEncoding]; 
} 

和我打電話從所謂的ViewController與代碼另一類這個方法

-(void)doLogin 
{ 
self.service = [[SyncCommunicationService alloc]init]; 
NSData *data = [self.service sendSynchronousRequest:strNewLoginRequest 
            returningResponse:&response 
               error:nil]; 
} 

我試圖調用此方法在後臺和主線程,但仍然委託方法沒有得到調用,我已經嘗試了許多來自同一網站的其他答案,但仍然無法解決這個問題,所以請任何人有線索我做錯了什麼。

回答

1

我想知道爲什麼會有人使用異步請求同步執行任務?更不用說這種奇怪的方式來等待while語句而不是dispatch_semaphore或類似的東西。

但是,爲什麼你甚至打擾委託?只需使用類方法sendSynchronousRequest:returningResponse:error :.我認爲,這就足夠你的情況

+0

我必須驗證服務器證書的SSL固定,所以我必須使用委託方法。 – Vaibhav

+0

在這種情況下,嘗試設置連接委託隊列'setDelegateQueue:' 讓此隊列屬於您的SyncCommunicationService –

+0

並且,您對'while'語句是否有信心等待操作?爲什麼不使用dispatch_semaphore呢?比你的'sendSynchronousRequest:returningResponse:error:'方法不會返回任何內容,並且可以從SyncCommunicationService的屬性中檢索響應數據(這就是我每次都在做的事情,我需要異步檢索數據) –

相關問題