如何使用NSURL Connection下载文件

时间:2013-12-09 12:57:10

标签: objective-c nsurlconnection

我知道这很愚蠢,但我不知道我错在哪里。我是NSURLConnections的新手。我必须使用NSURLConnection下载文件。这是我的代码:

NSURL *url = [NSURL URLWithString:@"http://www.comicbookresources.com/feed.php?feed=previews"];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];
[self.data appendData:self.data];
NSString  *filePath = [NSString stringWithFormat:@"%u/%@", NSDocumentDirectory,@"usman.pdf"];
[self.data writeToFile:filePath atomically:YES];
它看起来很荒谬,但我仍在问

编辑:对不起。我忘了添加单词:异步连接

1 个答案:

答案 0 :(得分:6)

试试这个......

NSURL *url = [NSURL URLWithString:@"http://www.comicbookresources.com/feed.php?feed=previews"];

NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30];
NSURLConnection *connection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];

然后取一个实例变量NSMutableData * mdata; //在.h文件中

之后实现NSURLConnectionDataDelegate方法

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
     mdata = [[NSMutableData alloc]init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
     [mdata appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
     NSString  *filePath = [NSString stringWithFormat:@"%u/%@", NSDocumentDirectory,@"usman.pdf"];
     [mdata writeToFile:filePath atomically:YES];
}

快乐的编码:)