2011-09-27 26 views
0

我有發送HTTP POST連接的代碼。我希望該方法等待,直到從服務器獲得響應才能繼續。我這樣做的原因是因爲我正在將新代碼(異步發佈與舊同步發佈)集成到我們的應用程序中,並且我正在尋找整個應用程序中的最小更改。等待NSURLConnection

舊的方法如下:

-(NSData*) postData: (NSString*) strData; 

該應用程序將調用它,併發送一個strData對象,它會鎖定在主線程,直到它得到的東西回來。這效率不高,但效果很好,但由於超時限制,我不得不改變它。

所以我的新方法(張貼在這裏完整的方法)如下:

-(NSData*) postData: (NSString*) strData 
{ 
    //start http request code 
    //postString is the STRING TO BE POSTED 
    NSString *postString; 
    //this is the string to send 
    postString = @"data="; 
    postString = [postString stringByAppendingString:strData]; 
    NSURL *url = [NSURL URLWithString:@"MYSERVERURL"]; 
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; 
    NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]]; 
    //setting prarameters of the POST connection 
    [request setHTTPMethod:@"POST"]; 
    [request addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
    [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; 
    [request addValue:@"en-US" forHTTPHeaderField:@"Content-Language"]; 
    [request setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]]; 
    [request setTimeoutInterval:20]; //one second for testing purposes 
    NSLog(@"%@",postString);  
    NSURLConnection *connection = [NSURLConnection connectionWithRequest:request delegate:self]; 
    [connection start]; 
    //end http request code 
    return receivedData; //this is set by a delegate somewhere else in the code 
} 

它發送代碼很好,但當然(和預期),沒有收到它足夠快,是正確返回。

你有什麼建議我可以這樣做:「停止」該方法等待返回任何東西,直到收到某些東西?我已經嘗試設置一個等待循環,等待BOOL,當收到所有數據時設置爲YES,但是該循環阻止了代碼的發送。我也嘗試將此方法的內容放入另一個方法中,並將其稱爲performSelectorInBackground,但當然,這也不起作用。我正在用盡想法,我非常感謝他們的幫助。

回答

2

做任何類型的同步COMM的主線程上是一個壞主意,但如果你不能重新構建在這一點上,然後看看:

+[NSURLConnection sendSynchronousRequest:returningResponse:error:]

的文檔可以發現here 。從討論:

A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.

但嚴重的是,看一看,有多少工作將參與異步執行的請求和接收通知的請求完成時。用戶的整體體驗會更好。

+0

嗯,我試圖保持目前的代碼(上圖),因爲它是因爲我需要實現小於240秒超時,只能用異步連接發生,而不是一個同步連接。 – Baub

0

您實際上正在那裏執行異步請求。

爲了執行同步請求,您應該在NSURLConnection類中使用+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error

雖然阻止應用程序的時候確實是一個壞主意,但這樣做通常是不鼓勵的。

乾杯