如何停止nsurlconnection?

时间:2012-03-12 09:24:43

标签: xcode download nsurlconnection

我正在使用与nsfile句柄的url连接来从服务器接收数据, 这是我使用的代码,

- (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];   
}

但不起作用,数据仍在接收,我是否想念一些东西? 或者我该怎么办?

1 个答案:

答案 0 :(得分:4)

已编辑: 这是我找到的解决方案:

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

添加self以取消当前连接...