2012-05-08 124 views
0

我關閉了我的網絡並運行我的ios程序。 然後停留程序。使用NSURLConnection連接失敗,如何重新連接?

當我打開我的網絡後。我的程序仍然停止。

我想在ios中重新連接NSURLConnection。

-(void) applistDBdownload 
{ 
NSString *file = [NSString stringWithFormat:@"http://sok129.cafxxx.com/oneapplist.sqlite3"]; 
NSURL *fileURL = [NSURL URLWithString:file]; 

NSURLRequest *req = [NSURLRequest requestWithURL:fileURL]; 
connect= [NSURLConnection connectionWithRequest:req delegate:self]; 

fileData = [[NSMutableData alloc] initWithLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
NSLog(@"fail"); -> come in when network off. 
        -> no come in when network on 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
      -> no come in when network on 
      -> come in when network off 
} 

1.如何重新連接?

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 
if(self.connect!=connection) 
{ 
    NSLog(@"noconnect"); 
    return; 
} 


[self.fileData appendData:data]; 
} 
    在此代碼區
  1. ,如果網絡關閉,我怎麼處理這個代碼?

回答

0

您通常應該告訴用戶出了點問題(例如使用UIAlertView)。您可以要求用戶嘗試再次連接。您也可以對用戶進行「透明」處理,並在用戶不知道發生了什麼的情況下重試。請再次致電applistDBdownload。雖然,我認爲你應該嘗試創建一些最適合你需要的邏輯(如果你知道你的網絡不斷下降,請在發出警告之前嘗試3到4次)。最後,您可以嘗試在服務器端進行更改(可能會收到較小的包,因此在您接收數據時網絡的百分比會更小)。

0

當你的網絡是反過來的, - (無效)連接:(NSURLConnection的*)連接didFailWithError:(NSError *)錯誤 會習慣這裏稱爲U可以添加以下行請求阿恩 [mConnection開始]; 當你開始連接時,如果你打開網絡,你可以得到正確的連接。

0

您可以使用處理重試HTTP請求的Apple MVCNetworkingMVCNetworking

下一個是從蘋果公司獲得的一種:MVCNetworking derived

這種方式意味着你首先應更多的代碼創建請求時,但請求失敗時,它將被賦予重嘗試給定的時間間隔。