2011-12-01 29 views
0

我有這樣的方法。當我的設備通過WiFi網絡連接時,它工作正常,但當它通過3G網絡連接時,它將我的應用程序凍結了幾秒鐘。 因此,因爲它是一個交互式應用程序,所以當它執行一些各種發佈請求時,它必須繼續運行,以便用戶可以繼續使用該應用程序。 任何解決方案?爲什麼我的應用程序在使用NSURLRequest發出POST請求時會凍結?

我試着減少[theRequest setTimeoutInterval:2.0];但是這並沒有解決我的問題。

// post request 
    - (void)postRequestWithURL:(NSString *)url 
           body:(NSString *)body 
         contentType:(NSString *)contentType 
          options:(NSDictionary *)dict 
    { 
     // set request 
     NSURL *requestURL = [NSURL URLWithString:url]; 
     NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init]; 


     if([dict count] > 0) 
     { 
      for (id key in dict) { 
       NSLog(@"[theRequest addValue:%@ forHTTPHeaderField:%@]", [dict valueForKey:key], key); 
       [theRequest addValue:[dict valueForKey:key] forHTTPHeaderField:key]; 
      } 
     } 

     if (contentType != nil) { 
      [theRequest addValue:contentType forHTTPHeaderField:@"Content-type"]; 
     } 

     [theRequest setURL:requestURL]; 
     [theRequest setTimeoutInterval:2.0]; 
     [theRequest setHTTPMethod:@"POST"]; 
     [theRequest setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding]]; 
     [self.oauthAuthentication authorizeRequest:theRequest]; 
     // make request 
     //responseData = [NSURLConnection sendSynchronousRequest:theRequest 
     //         returningResponse:&response 
     //            error:&error]; 

     NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; 
     self.web = conn; 

     [conn release]; 

     NSLog(@"########## REQUEST URL: %@", url); 




     // request and response sending and returning objects 
    } 

回答

1

它凍結你的應用程序,因爲你告訴它。你已經立即通過了YES。這意味着它將在該線程上啓動連接並等待完成。我想你正在做的這個線程將是主線程 - 也處理UI等:)

你需要使用像connectionWithRequest:delegate: - 這將在後臺運行請求,並告訴你什麼時候完成。

PS你沒有發現的WiFi錯誤的原因是因爲數據是如此之快送你可能不會注意到你的應用程序:)

PPS的原因超時沒有解決它暫停是因爲該請求沒有超時 - 它只是獲取數據很慢:)


編輯

事情是這樣的:

self.web = [NSURLConnection connectionWithRequest:request delegate:self]; 
+0

感謝您的回答!所以如何編輯我的NSURLConnection * conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES]; ??我不能用performselectorinbackground做到這一點? –

+0

我編輯了我的問題 - 調用'connectionWithRequest:delegate:'會自動在後臺啓動它 - 你不需要考慮'performSelectorInBackground:'或類似的東西。 – deanWombourne

相關問題