2012-03-12 94 views
0

我使用的是nsfile手柄的URL連接到服務器,從接收數據, 這是我使用的代碼,如何停止nsurlconnection?

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response { 

filename = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"Ep1.mp4"; 

[[NSFileManager defaultManager] createFileAtPath:filename contents:nil attributes:nil]; 
file =[NSFileHandle fileHandleForUpdatingAtPath:filename] ; 

if (file) { 

    [file seekToEndOfFile]; 
}} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { 


if (file) { 

    [file seekToEndOfFile]; 

} [file writeData:data]; } 


- (void)connectionDidFinishLoading:(NSURLConnection*)connection { 


[file closeFile]; 
} 


-(void)downloadFile{ 

targetURL = [NSURL URLWithString:@"http://some url "]; 

DownloadRequest = [NSURLRequest requestWithURL:targetURL cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:50.0]; 
DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self]; 

if (DownloadConnection) { 
    receivedData = [NSMutableData data]; 
} 
} 

我想停止連接,下載文件的時候,所以,我創建按鈕 --->

- (void)buttonPressed:(id)sender 
{ 
DownloadConnection = [[NSURLConnection alloc] initWithRequest: DownloadRequest delegate:self]; 
[ DownloadConnection cancel]; 
} 

但不工作,數據仍在接受,我錯過理解的東西嗎? 或我能做些什麼?

+0

見[這裏](http://stackoverflow.com/a/7229304/845115) – 2012-03-12 09:37:00

+0

謝謝〜我想念「自我」....哈哈 – cmin 2012-03-12 10:10:49

回答

4

編輯: 這是我找到了解決辦法:

- (void)buttonPressed:(id)sender 
{ 
DownloadConnection = [[NSURLConnection alloc] initWithRequest: DownloadRequest delegate:self]; 
[ self.DownloadConnection cancel]; 
} 

添加自取消當前連接...