2012-09-24 24 views
2

我正在開發一個連接到服務器並從中下載數據的項目。如果連接中斷,我喜歡支持恢復下載。我的方法是將下載的數據部分保存到目標文件;並且如果連接被中斷,我想使用連接標記下載的部分:didWriteData:totalBytesWritten:expectedTotalBytes,稍後從服務器的停止部分恢復。NSURLConnectionDownloadDelegate方法沒有被調用

我的代碼:

- (IBAction)connectToServer:(UIButton *)sender 
{ 
    // setup url and send request to server 
    NSURL *url = [NSURL URLWithString:BASED_URL]; 
    self.urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0]; 
    self.urlConnection = [[NSURLConnection alloc] initWithRequest:self.urlRequest delegate:self]; 

    // start receive data if connection established 
    if (self.urlConnection){ 
    self.receivedData = [NSMutableData data]; 
    NSLog(@"starting to receive data"); 

} else { 
    // handle error 
    NSLog(@"failed to connect to server"); 
    } 
} 

- (void)doSomethingWithData 
{ 
    // handle data here 
} 


#pragma NSURLConnectionDataDelegate 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse  *)response 
{ 
    [self.receivedData setLength:0]; 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    // received data 
    [self.receivedData appendData:data]; 
} 

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error 
{ 
    // error connection 
    NSLog(@"connection failed"); 
} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    NSLog(@"Data receiving succeed, received: %d bytes of data", [self.receivedData length]); 

} 

- (void)connection:(NSURLConnection *)connection didWriteData:(long long)bytesWritten totalBytesWritten:(long long)totalBytesWritten expectedTotalBytes:(long long)expectedTotalBytes 
{ 
    NSLog(@"not getting called"); 
} 

我的問題是怎麼來的 「連接:didWriteData:totalBytesWritten:expectedTotalBytes」 的方法永遠不會叫什麼名字?

非常感謝! 克里斯

回答

1

具有u加入這個在.h文件中:

@interface yourViewContoller : UIViewController <NSURLConnectionDataDelegate, NSURLConnectionDelegate> 
0

根據Apple's documentation

的NSURLConnectionDownloadDelegate協議描述應該由NSURLConnection的實例的委託來實現的方法創建使用報亭套件的downloadWithDelegate:方法。

此外,它說:

如果您是直接使用NSURLConnection的,你的委託類應該改爲實現在NSURLConnectionDataDelegate協議中定義的方法。