2012-03-12 53 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]; 
} 

添加自取消当前连接...